1use agent_settings::{AgentSettings, SUMMARIZE_THREAD_PROMPT};
2use anyhow::{Context as _, Result, bail};
3use assistant_slash_command::{
4 SlashCommandContent, SlashCommandEvent, SlashCommandLine, SlashCommandOutputSection,
5 SlashCommandResult, SlashCommandWorkingSet,
6};
7use assistant_slash_commands::FileCommandMetadata;
8use client::{self, ModelRequestUsage, RequestUsage, proto, telemetry::Telemetry};
9use clock::ReplicaId;
10use cloud_llm_client::{CompletionIntent, CompletionRequestStatus, UsageLimit};
11use collections::{HashMap, HashSet};
12use fs::{Fs, RenameOptions};
13use futures::{FutureExt, StreamExt, future::Shared};
14use gpui::{
15 App, AppContext as _, Context, Entity, EventEmitter, RenderImage, SharedString, Subscription,
16 Task,
17};
18use language::{AnchorRangeExt, Bias, Buffer, LanguageRegistry, OffsetRangeExt, Point, ToOffset};
19use language_model::{
20 LanguageModel, LanguageModelCacheConfiguration, LanguageModelCompletionEvent,
21 LanguageModelImage, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
22 LanguageModelToolUseId, MessageContent, PaymentRequiredError, Role, StopReason,
23 report_assistant_event,
24};
25use open_ai::Model as OpenAiModel;
26use paths::text_threads_dir;
27use project::Project;
28use prompt_store::PromptBuilder;
29use serde::{Deserialize, Serialize};
30use settings::Settings;
31use smallvec::SmallVec;
32use std::{
33 cmp::{Ordering, max},
34 fmt::{Debug, Write as _},
35 iter, mem,
36 ops::Range,
37 path::Path,
38 sync::Arc,
39 time::{Duration, Instant},
40};
41use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
42use text::{BufferSnapshot, ToPoint};
43use ui::IconName;
44use util::{ResultExt, TryFutureExt, post_inc};
45use uuid::Uuid;
46
47#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
48pub struct TextThreadId(String);
49
50impl TextThreadId {
51 pub fn new() -> Self {
52 Self(Uuid::new_v4().to_string())
53 }
54
55 pub fn from_proto(id: String) -> Self {
56 Self(id)
57 }
58
59 pub fn to_proto(&self) -> String {
60 self.0.clone()
61 }
62}
63
64#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
65pub struct MessageId(pub clock::Lamport);
66
67impl MessageId {
68 pub fn as_u64(self) -> u64 {
69 self.0.as_u64()
70 }
71}
72
73#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
74pub enum MessageStatus {
75 Pending,
76 Done,
77 Error(SharedString),
78 Canceled,
79}
80
81impl MessageStatus {
82 pub fn from_proto(status: proto::ContextMessageStatus) -> MessageStatus {
83 match status.variant {
84 Some(proto::context_message_status::Variant::Pending(_)) => MessageStatus::Pending,
85 Some(proto::context_message_status::Variant::Done(_)) => MessageStatus::Done,
86 Some(proto::context_message_status::Variant::Error(error)) => {
87 MessageStatus::Error(error.message.into())
88 }
89 Some(proto::context_message_status::Variant::Canceled(_)) => MessageStatus::Canceled,
90 None => MessageStatus::Pending,
91 }
92 }
93
94 pub fn to_proto(&self) -> proto::ContextMessageStatus {
95 match self {
96 MessageStatus::Pending => proto::ContextMessageStatus {
97 variant: Some(proto::context_message_status::Variant::Pending(
98 proto::context_message_status::Pending {},
99 )),
100 },
101 MessageStatus::Done => proto::ContextMessageStatus {
102 variant: Some(proto::context_message_status::Variant::Done(
103 proto::context_message_status::Done {},
104 )),
105 },
106 MessageStatus::Error(message) => proto::ContextMessageStatus {
107 variant: Some(proto::context_message_status::Variant::Error(
108 proto::context_message_status::Error {
109 message: message.to_string(),
110 },
111 )),
112 },
113 MessageStatus::Canceled => proto::ContextMessageStatus {
114 variant: Some(proto::context_message_status::Variant::Canceled(
115 proto::context_message_status::Canceled {},
116 )),
117 },
118 }
119 }
120}
121
122#[derive(Clone, Debug)]
123pub enum TextThreadOperation {
124 InsertMessage {
125 anchor: MessageAnchor,
126 metadata: MessageMetadata,
127 version: clock::Global,
128 },
129 UpdateMessage {
130 message_id: MessageId,
131 metadata: MessageMetadata,
132 version: clock::Global,
133 },
134 UpdateSummary {
135 summary: TextThreadSummaryContent,
136 version: clock::Global,
137 },
138 SlashCommandStarted {
139 id: InvokedSlashCommandId,
140 output_range: Range<language::Anchor>,
141 name: String,
142 version: clock::Global,
143 },
144 SlashCommandFinished {
145 id: InvokedSlashCommandId,
146 timestamp: clock::Lamport,
147 error_message: Option<String>,
148 version: clock::Global,
149 },
150 SlashCommandOutputSectionAdded {
151 timestamp: clock::Lamport,
152 section: SlashCommandOutputSection<language::Anchor>,
153 version: clock::Global,
154 },
155 ThoughtProcessOutputSectionAdded {
156 timestamp: clock::Lamport,
157 section: ThoughtProcessOutputSection<language::Anchor>,
158 version: clock::Global,
159 },
160 BufferOperation(language::Operation),
161}
162
163impl TextThreadOperation {
164 pub fn from_proto(op: proto::ContextOperation) -> Result<Self> {
165 match op.variant.context("invalid variant")? {
166 proto::context_operation::Variant::InsertMessage(insert) => {
167 let message = insert.message.context("invalid message")?;
168 let id = MessageId(language::proto::deserialize_timestamp(
169 message.id.context("invalid id")?,
170 ));
171 Ok(Self::InsertMessage {
172 anchor: MessageAnchor {
173 id,
174 start: language::proto::deserialize_anchor(
175 message.start.context("invalid anchor")?,
176 )
177 .context("invalid anchor")?,
178 },
179 metadata: MessageMetadata {
180 role: Role::from_proto(message.role),
181 status: MessageStatus::from_proto(
182 message.status.context("invalid status")?,
183 ),
184 timestamp: id.0,
185 cache: None,
186 },
187 version: language::proto::deserialize_version(&insert.version),
188 })
189 }
190 proto::context_operation::Variant::UpdateMessage(update) => Ok(Self::UpdateMessage {
191 message_id: MessageId(language::proto::deserialize_timestamp(
192 update.message_id.context("invalid message id")?,
193 )),
194 metadata: MessageMetadata {
195 role: Role::from_proto(update.role),
196 status: MessageStatus::from_proto(update.status.context("invalid status")?),
197 timestamp: language::proto::deserialize_timestamp(
198 update.timestamp.context("invalid timestamp")?,
199 ),
200 cache: None,
201 },
202 version: language::proto::deserialize_version(&update.version),
203 }),
204 proto::context_operation::Variant::UpdateSummary(update) => Ok(Self::UpdateSummary {
205 summary: TextThreadSummaryContent {
206 text: update.summary,
207 done: update.done,
208 timestamp: language::proto::deserialize_timestamp(
209 update.timestamp.context("invalid timestamp")?,
210 ),
211 },
212 version: language::proto::deserialize_version(&update.version),
213 }),
214 proto::context_operation::Variant::SlashCommandStarted(message) => {
215 Ok(Self::SlashCommandStarted {
216 id: InvokedSlashCommandId(language::proto::deserialize_timestamp(
217 message.id.context("invalid id")?,
218 )),
219 output_range: language::proto::deserialize_anchor_range(
220 message.output_range.context("invalid range")?,
221 )?,
222 name: message.name,
223 version: language::proto::deserialize_version(&message.version),
224 })
225 }
226 proto::context_operation::Variant::SlashCommandOutputSectionAdded(message) => {
227 let section = message.section.context("missing section")?;
228 Ok(Self::SlashCommandOutputSectionAdded {
229 timestamp: language::proto::deserialize_timestamp(
230 message.timestamp.context("missing timestamp")?,
231 ),
232 section: SlashCommandOutputSection {
233 range: language::proto::deserialize_anchor_range(
234 section.range.context("invalid range")?,
235 )?,
236 icon: section.icon_name.parse()?,
237 label: section.label.into(),
238 metadata: section
239 .metadata
240 .and_then(|metadata| serde_json::from_str(&metadata).log_err()),
241 },
242 version: language::proto::deserialize_version(&message.version),
243 })
244 }
245 proto::context_operation::Variant::SlashCommandCompleted(message) => {
246 Ok(Self::SlashCommandFinished {
247 id: InvokedSlashCommandId(language::proto::deserialize_timestamp(
248 message.id.context("invalid id")?,
249 )),
250 timestamp: language::proto::deserialize_timestamp(
251 message.timestamp.context("missing timestamp")?,
252 ),
253 error_message: message.error_message,
254 version: language::proto::deserialize_version(&message.version),
255 })
256 }
257 proto::context_operation::Variant::ThoughtProcessOutputSectionAdded(message) => {
258 let section = message.section.context("missing section")?;
259 Ok(Self::ThoughtProcessOutputSectionAdded {
260 timestamp: language::proto::deserialize_timestamp(
261 message.timestamp.context("missing timestamp")?,
262 ),
263 section: ThoughtProcessOutputSection {
264 range: language::proto::deserialize_anchor_range(
265 section.range.context("invalid range")?,
266 )?,
267 },
268 version: language::proto::deserialize_version(&message.version),
269 })
270 }
271 proto::context_operation::Variant::BufferOperation(op) => Ok(Self::BufferOperation(
272 language::proto::deserialize_operation(
273 op.operation.context("invalid buffer operation")?,
274 )?,
275 )),
276 }
277 }
278
279 pub fn to_proto(&self) -> proto::ContextOperation {
280 match self {
281 Self::InsertMessage {
282 anchor,
283 metadata,
284 version,
285 } => proto::ContextOperation {
286 variant: Some(proto::context_operation::Variant::InsertMessage(
287 proto::context_operation::InsertMessage {
288 message: Some(proto::ContextMessage {
289 id: Some(language::proto::serialize_timestamp(anchor.id.0)),
290 start: Some(language::proto::serialize_anchor(&anchor.start)),
291 role: metadata.role.to_proto() as i32,
292 status: Some(metadata.status.to_proto()),
293 }),
294 version: language::proto::serialize_version(version),
295 },
296 )),
297 },
298 Self::UpdateMessage {
299 message_id,
300 metadata,
301 version,
302 } => proto::ContextOperation {
303 variant: Some(proto::context_operation::Variant::UpdateMessage(
304 proto::context_operation::UpdateMessage {
305 message_id: Some(language::proto::serialize_timestamp(message_id.0)),
306 role: metadata.role.to_proto() as i32,
307 status: Some(metadata.status.to_proto()),
308 timestamp: Some(language::proto::serialize_timestamp(metadata.timestamp)),
309 version: language::proto::serialize_version(version),
310 },
311 )),
312 },
313 Self::UpdateSummary { summary, version } => proto::ContextOperation {
314 variant: Some(proto::context_operation::Variant::UpdateSummary(
315 proto::context_operation::UpdateSummary {
316 summary: summary.text.clone(),
317 done: summary.done,
318 timestamp: Some(language::proto::serialize_timestamp(summary.timestamp)),
319 version: language::proto::serialize_version(version),
320 },
321 )),
322 },
323 Self::SlashCommandStarted {
324 id,
325 output_range,
326 name,
327 version,
328 } => proto::ContextOperation {
329 variant: Some(proto::context_operation::Variant::SlashCommandStarted(
330 proto::context_operation::SlashCommandStarted {
331 id: Some(language::proto::serialize_timestamp(id.0)),
332 output_range: Some(language::proto::serialize_anchor_range(
333 output_range.clone(),
334 )),
335 name: name.clone(),
336 version: language::proto::serialize_version(version),
337 },
338 )),
339 },
340 Self::SlashCommandOutputSectionAdded {
341 timestamp,
342 section,
343 version,
344 } => proto::ContextOperation {
345 variant: Some(
346 proto::context_operation::Variant::SlashCommandOutputSectionAdded(
347 proto::context_operation::SlashCommandOutputSectionAdded {
348 timestamp: Some(language::proto::serialize_timestamp(*timestamp)),
349 section: Some({
350 let icon_name: &'static str = section.icon.into();
351 proto::SlashCommandOutputSection {
352 range: Some(language::proto::serialize_anchor_range(
353 section.range.clone(),
354 )),
355 icon_name: icon_name.to_string(),
356 label: section.label.to_string(),
357 metadata: section.metadata.as_ref().and_then(|metadata| {
358 serde_json::to_string(metadata).log_err()
359 }),
360 }
361 }),
362 version: language::proto::serialize_version(version),
363 },
364 ),
365 ),
366 },
367 Self::SlashCommandFinished {
368 id,
369 timestamp,
370 error_message,
371 version,
372 } => proto::ContextOperation {
373 variant: Some(proto::context_operation::Variant::SlashCommandCompleted(
374 proto::context_operation::SlashCommandCompleted {
375 id: Some(language::proto::serialize_timestamp(id.0)),
376 timestamp: Some(language::proto::serialize_timestamp(*timestamp)),
377 error_message: error_message.clone(),
378 version: language::proto::serialize_version(version),
379 },
380 )),
381 },
382 Self::ThoughtProcessOutputSectionAdded {
383 timestamp,
384 section,
385 version,
386 } => proto::ContextOperation {
387 variant: Some(
388 proto::context_operation::Variant::ThoughtProcessOutputSectionAdded(
389 proto::context_operation::ThoughtProcessOutputSectionAdded {
390 timestamp: Some(language::proto::serialize_timestamp(*timestamp)),
391 section: Some({
392 proto::ThoughtProcessOutputSection {
393 range: Some(language::proto::serialize_anchor_range(
394 section.range.clone(),
395 )),
396 }
397 }),
398 version: language::proto::serialize_version(version),
399 },
400 ),
401 ),
402 },
403 Self::BufferOperation(operation) => proto::ContextOperation {
404 variant: Some(proto::context_operation::Variant::BufferOperation(
405 proto::context_operation::BufferOperation {
406 operation: Some(language::proto::serialize_operation(operation)),
407 },
408 )),
409 },
410 }
411 }
412
413 fn timestamp(&self) -> clock::Lamport {
414 match self {
415 Self::InsertMessage { anchor, .. } => anchor.id.0,
416 Self::UpdateMessage { metadata, .. } => metadata.timestamp,
417 Self::UpdateSummary { summary, .. } => summary.timestamp,
418 Self::SlashCommandStarted { id, .. } => id.0,
419 Self::SlashCommandOutputSectionAdded { timestamp, .. }
420 | Self::SlashCommandFinished { timestamp, .. }
421 | Self::ThoughtProcessOutputSectionAdded { timestamp, .. } => *timestamp,
422 Self::BufferOperation(_) => {
423 panic!("reading the timestamp of a buffer operation is not supported")
424 }
425 }
426 }
427
428 /// Returns the current version of the context operation.
429 pub fn version(&self) -> &clock::Global {
430 match self {
431 Self::InsertMessage { version, .. }
432 | Self::UpdateMessage { version, .. }
433 | Self::UpdateSummary { version, .. }
434 | Self::SlashCommandStarted { version, .. }
435 | Self::SlashCommandOutputSectionAdded { version, .. }
436 | Self::SlashCommandFinished { version, .. }
437 | Self::ThoughtProcessOutputSectionAdded { version, .. } => version,
438 Self::BufferOperation(_) => {
439 panic!("reading the version of a buffer operation is not supported")
440 }
441 }
442 }
443}
444
445#[derive(Debug, Clone)]
446pub enum TextThreadEvent {
447 ShowAssistError(SharedString),
448 ShowPaymentRequiredError,
449 MessagesEdited,
450 SummaryChanged,
451 SummaryGenerated,
452 PathChanged {
453 old_path: Option<Arc<Path>>,
454 new_path: Arc<Path>,
455 },
456 StreamedCompletion,
457 StartedThoughtProcess(Range<language::Anchor>),
458 EndedThoughtProcess(language::Anchor),
459 InvokedSlashCommandChanged {
460 command_id: InvokedSlashCommandId,
461 },
462 ParsedSlashCommandsUpdated {
463 removed: Vec<Range<language::Anchor>>,
464 updated: Vec<ParsedSlashCommand>,
465 },
466 SlashCommandOutputSectionAdded {
467 section: SlashCommandOutputSection<language::Anchor>,
468 },
469 Operation(TextThreadOperation),
470}
471
472#[derive(Clone, Debug, Eq, PartialEq)]
473pub enum TextThreadSummary {
474 Pending,
475 Content(TextThreadSummaryContent),
476 Error,
477}
478
479#[derive(Clone, Debug, Eq, PartialEq)]
480pub struct TextThreadSummaryContent {
481 pub text: String,
482 pub done: bool,
483 pub timestamp: clock::Lamport,
484}
485
486impl TextThreadSummary {
487 pub const DEFAULT: &str = "New Text Thread";
488
489 pub fn or_default(&self) -> SharedString {
490 self.unwrap_or(Self::DEFAULT)
491 }
492
493 pub fn unwrap_or(&self, message: impl Into<SharedString>) -> SharedString {
494 self.content()
495 .map_or_else(|| message.into(), |content| content.text.clone().into())
496 }
497
498 pub fn content(&self) -> Option<&TextThreadSummaryContent> {
499 match self {
500 TextThreadSummary::Content(content) => Some(content),
501 TextThreadSummary::Pending | TextThreadSummary::Error => None,
502 }
503 }
504
505 fn content_as_mut(&mut self) -> Option<&mut TextThreadSummaryContent> {
506 match self {
507 TextThreadSummary::Content(content) => Some(content),
508 TextThreadSummary::Pending | TextThreadSummary::Error => None,
509 }
510 }
511
512 fn content_or_set_empty(&mut self) -> &mut TextThreadSummaryContent {
513 match self {
514 TextThreadSummary::Content(content) => content,
515 TextThreadSummary::Pending | TextThreadSummary::Error => {
516 let content = TextThreadSummaryContent {
517 text: "".to_string(),
518 done: false,
519 timestamp: clock::Lamport::MIN,
520 };
521 *self = TextThreadSummary::Content(content);
522 self.content_as_mut().unwrap()
523 }
524 }
525 }
526
527 pub fn is_pending(&self) -> bool {
528 matches!(self, TextThreadSummary::Pending)
529 }
530
531 fn timestamp(&self) -> Option<clock::Lamport> {
532 match self {
533 TextThreadSummary::Content(content) => Some(content.timestamp),
534 TextThreadSummary::Pending | TextThreadSummary::Error => None,
535 }
536 }
537}
538
539impl PartialOrd for TextThreadSummary {
540 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
541 self.timestamp().partial_cmp(&other.timestamp())
542 }
543}
544
545#[derive(Clone, Debug, Eq, PartialEq)]
546pub struct MessageAnchor {
547 pub id: MessageId,
548 pub start: language::Anchor,
549}
550
551#[derive(Clone, Debug, Eq, PartialEq)]
552pub enum CacheStatus {
553 Pending,
554 Cached,
555}
556
557#[derive(Clone, Debug, Eq, PartialEq)]
558pub struct MessageCacheMetadata {
559 pub is_anchor: bool,
560 pub is_final_anchor: bool,
561 pub status: CacheStatus,
562 pub cached_at: clock::Global,
563}
564
565#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
566pub struct MessageMetadata {
567 pub role: Role,
568 pub status: MessageStatus,
569 pub timestamp: clock::Lamport,
570 #[serde(skip)]
571 pub cache: Option<MessageCacheMetadata>,
572}
573
574impl From<&Message> for MessageMetadata {
575 fn from(message: &Message) -> Self {
576 Self {
577 role: message.role,
578 status: message.status.clone(),
579 timestamp: message.id.0,
580 cache: message.cache.clone(),
581 }
582 }
583}
584
585impl MessageMetadata {
586 pub fn is_cache_valid(&self, buffer: &BufferSnapshot, range: &Range<usize>) -> bool {
587 match &self.cache {
588 Some(MessageCacheMetadata { cached_at, .. }) => !buffer.has_edits_since_in_range(
589 cached_at,
590 Range {
591 start: buffer.anchor_at(range.start, Bias::Right),
592 end: buffer.anchor_at(range.end, Bias::Left),
593 },
594 ),
595 _ => false,
596 }
597 }
598}
599
600#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
601pub struct ThoughtProcessOutputSection<T> {
602 pub range: Range<T>,
603}
604
605impl ThoughtProcessOutputSection<language::Anchor> {
606 pub fn is_valid(&self, buffer: &language::TextBuffer) -> bool {
607 self.range.start.is_valid(buffer) && !self.range.to_offset(buffer).is_empty()
608 }
609}
610
611#[derive(Clone, Debug)]
612pub struct Message {
613 pub offset_range: Range<usize>,
614 pub index_range: Range<usize>,
615 pub anchor_range: Range<language::Anchor>,
616 pub id: MessageId,
617 pub role: Role,
618 pub status: MessageStatus,
619 pub cache: Option<MessageCacheMetadata>,
620}
621
622#[derive(Debug, Clone)]
623pub enum Content {
624 Image {
625 anchor: language::Anchor,
626 image_id: u64,
627 render_image: Arc<RenderImage>,
628 image: Shared<Task<Option<LanguageModelImage>>>,
629 },
630}
631
632impl Content {
633 fn range(&self) -> Range<language::Anchor> {
634 match self {
635 Self::Image { anchor, .. } => *anchor..*anchor,
636 }
637 }
638
639 fn cmp(&self, other: &Self, buffer: &BufferSnapshot) -> Ordering {
640 let self_range = self.range();
641 let other_range = other.range();
642 if self_range.end.cmp(&other_range.start, buffer).is_lt() {
643 Ordering::Less
644 } else if self_range.start.cmp(&other_range.end, buffer).is_gt() {
645 Ordering::Greater
646 } else {
647 Ordering::Equal
648 }
649 }
650}
651
652struct PendingCompletion {
653 id: usize,
654 assistant_message_id: MessageId,
655 _task: Task<()>,
656}
657
658#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
659pub struct InvokedSlashCommandId(clock::Lamport);
660
661pub struct TextThread {
662 id: TextThreadId,
663 timestamp: clock::Lamport,
664 version: clock::Global,
665 pub(crate) pending_ops: Vec<TextThreadOperation>,
666 operations: Vec<TextThreadOperation>,
667 buffer: Entity<Buffer>,
668 pub(crate) parsed_slash_commands: Vec<ParsedSlashCommand>,
669 invoked_slash_commands: HashMap<InvokedSlashCommandId, InvokedSlashCommand>,
670 edits_since_last_parse: language::Subscription,
671 slash_commands: Arc<SlashCommandWorkingSet>,
672 pub(crate) slash_command_output_sections: Vec<SlashCommandOutputSection<language::Anchor>>,
673 thought_process_output_sections: Vec<ThoughtProcessOutputSection<language::Anchor>>,
674 pub(crate) message_anchors: Vec<MessageAnchor>,
675 contents: Vec<Content>,
676 pub(crate) messages_metadata: HashMap<MessageId, MessageMetadata>,
677 summary: TextThreadSummary,
678 summary_task: Task<Option<()>>,
679 completion_count: usize,
680 pending_completions: Vec<PendingCompletion>,
681 pub(crate) token_count: Option<u64>,
682 pending_token_count: Task<Option<()>>,
683 pending_save: Task<Result<()>>,
684 pending_cache_warming_task: Task<Option<()>>,
685 path: Option<Arc<Path>>,
686 _subscriptions: Vec<Subscription>,
687 telemetry: Option<Arc<Telemetry>>,
688 language_registry: Arc<LanguageRegistry>,
689 project: Option<Entity<Project>>,
690 prompt_builder: Arc<PromptBuilder>,
691 completion_mode: agent_settings::CompletionMode,
692}
693
694trait ContextAnnotation {
695 fn range(&self) -> &Range<language::Anchor>;
696}
697
698impl ContextAnnotation for ParsedSlashCommand {
699 fn range(&self) -> &Range<language::Anchor> {
700 &self.source_range
701 }
702}
703
704impl EventEmitter<TextThreadEvent> for TextThread {}
705
706impl TextThread {
707 pub fn local(
708 language_registry: Arc<LanguageRegistry>,
709 project: Option<Entity<Project>>,
710 telemetry: Option<Arc<Telemetry>>,
711 prompt_builder: Arc<PromptBuilder>,
712 slash_commands: Arc<SlashCommandWorkingSet>,
713 cx: &mut Context<Self>,
714 ) -> Self {
715 Self::new(
716 TextThreadId::new(),
717 ReplicaId::default(),
718 language::Capability::ReadWrite,
719 language_registry,
720 prompt_builder,
721 slash_commands,
722 project,
723 telemetry,
724 cx,
725 )
726 }
727
728 pub fn completion_mode(&self) -> agent_settings::CompletionMode {
729 self.completion_mode
730 }
731
732 pub fn set_completion_mode(&mut self, completion_mode: agent_settings::CompletionMode) {
733 self.completion_mode = completion_mode;
734 }
735
736 pub fn new(
737 id: TextThreadId,
738 replica_id: ReplicaId,
739 capability: language::Capability,
740 language_registry: Arc<LanguageRegistry>,
741 prompt_builder: Arc<PromptBuilder>,
742 slash_commands: Arc<SlashCommandWorkingSet>,
743 project: Option<Entity<Project>>,
744 telemetry: Option<Arc<Telemetry>>,
745 cx: &mut Context<Self>,
746 ) -> Self {
747 let buffer = cx.new(|cx| {
748 let buffer = Buffer::remote(
749 language::BufferId::new(1).unwrap(),
750 replica_id,
751 capability,
752 "",
753 cx.background_executor(),
754 );
755 buffer.set_language_registry(language_registry.clone());
756 buffer
757 });
758 let edits_since_last_slash_command_parse =
759 buffer.update(cx, |buffer, _| buffer.subscribe());
760 let mut this = Self {
761 id,
762 timestamp: clock::Lamport::new(replica_id),
763 version: clock::Global::new(),
764 pending_ops: Vec::new(),
765 operations: Vec::new(),
766 message_anchors: Default::default(),
767 contents: Default::default(),
768 messages_metadata: Default::default(),
769 parsed_slash_commands: Vec::new(),
770 invoked_slash_commands: HashMap::default(),
771 slash_command_output_sections: Vec::new(),
772 thought_process_output_sections: Vec::new(),
773 edits_since_last_parse: edits_since_last_slash_command_parse,
774 summary: TextThreadSummary::Pending,
775 summary_task: Task::ready(None),
776 completion_count: Default::default(),
777 pending_completions: Default::default(),
778 token_count: None,
779 pending_token_count: Task::ready(None),
780 pending_cache_warming_task: Task::ready(None),
781 _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
782 pending_save: Task::ready(Ok(())),
783 completion_mode: AgentSettings::get_global(cx).preferred_completion_mode,
784 path: None,
785 buffer,
786 telemetry,
787 project,
788 language_registry,
789 slash_commands,
790 prompt_builder,
791 };
792
793 let first_message_id = MessageId(clock::Lamport {
794 replica_id: ReplicaId::LOCAL,
795 value: 0,
796 });
797 let message = MessageAnchor {
798 id: first_message_id,
799 start: language::Anchor::MIN,
800 };
801 this.messages_metadata.insert(
802 first_message_id,
803 MessageMetadata {
804 role: Role::User,
805 status: MessageStatus::Done,
806 timestamp: first_message_id.0,
807 cache: None,
808 },
809 );
810 this.message_anchors.push(message);
811
812 this.set_language(cx);
813 this.count_remaining_tokens(cx);
814 this
815 }
816
817 pub(crate) fn serialize(&self, cx: &App) -> SavedTextThread {
818 let buffer = self.buffer.read(cx);
819 SavedTextThread {
820 id: Some(self.id.clone()),
821 zed: "context".into(),
822 version: SavedTextThread::VERSION.into(),
823 text: buffer.text(),
824 messages: self
825 .messages(cx)
826 .map(|message| SavedMessage {
827 id: message.id,
828 start: message.offset_range.start,
829 metadata: self.messages_metadata[&message.id].clone(),
830 })
831 .collect(),
832 summary: self
833 .summary
834 .content()
835 .map(|summary| summary.text.clone())
836 .unwrap_or_default(),
837 slash_command_output_sections: self
838 .slash_command_output_sections
839 .iter()
840 .filter_map(|section| {
841 if section.is_valid(buffer) {
842 let range = section.range.to_offset(buffer);
843 Some(assistant_slash_command::SlashCommandOutputSection {
844 range,
845 icon: section.icon,
846 label: section.label.clone(),
847 metadata: section.metadata.clone(),
848 })
849 } else {
850 None
851 }
852 })
853 .collect(),
854 thought_process_output_sections: self
855 .thought_process_output_sections
856 .iter()
857 .filter_map(|section| {
858 if section.is_valid(buffer) {
859 let range = section.range.to_offset(buffer);
860 Some(ThoughtProcessOutputSection { range })
861 } else {
862 None
863 }
864 })
865 .collect(),
866 }
867 }
868
869 pub fn deserialize(
870 saved_context: SavedTextThread,
871 path: Arc<Path>,
872 language_registry: Arc<LanguageRegistry>,
873 prompt_builder: Arc<PromptBuilder>,
874 slash_commands: Arc<SlashCommandWorkingSet>,
875 project: Option<Entity<Project>>,
876 telemetry: Option<Arc<Telemetry>>,
877 cx: &mut Context<Self>,
878 ) -> Self {
879 let id = saved_context.id.clone().unwrap_or_else(TextThreadId::new);
880 let mut this = Self::new(
881 id,
882 ReplicaId::default(),
883 language::Capability::ReadWrite,
884 language_registry,
885 prompt_builder,
886 slash_commands,
887 project,
888 telemetry,
889 cx,
890 );
891 this.path = Some(path);
892 this.buffer.update(cx, |buffer, cx| {
893 buffer.set_text(saved_context.text.as_str(), cx)
894 });
895 let operations = saved_context.into_ops(&this.buffer, cx);
896 this.apply_ops(operations, cx);
897 this
898 }
899
900 pub fn id(&self) -> &TextThreadId {
901 &self.id
902 }
903
904 pub fn replica_id(&self) -> ReplicaId {
905 self.timestamp.replica_id
906 }
907
908 pub fn version(&self, cx: &App) -> TextThreadVersion {
909 TextThreadVersion {
910 text_thread: self.version.clone(),
911 buffer: self.buffer.read(cx).version(),
912 }
913 }
914
915 pub fn slash_commands(&self) -> &Arc<SlashCommandWorkingSet> {
916 &self.slash_commands
917 }
918
919 pub fn set_capability(&mut self, capability: language::Capability, cx: &mut Context<Self>) {
920 self.buffer
921 .update(cx, |buffer, cx| buffer.set_capability(capability, cx));
922 }
923
924 fn next_timestamp(&mut self) -> clock::Lamport {
925 let timestamp = self.timestamp.tick();
926 self.version.observe(timestamp);
927 timestamp
928 }
929
930 pub fn serialize_ops(
931 &self,
932 since: &TextThreadVersion,
933 cx: &App,
934 ) -> Task<Vec<proto::ContextOperation>> {
935 let buffer_ops = self
936 .buffer
937 .read(cx)
938 .serialize_ops(Some(since.buffer.clone()), cx);
939
940 let mut context_ops = self
941 .operations
942 .iter()
943 .filter(|op| !since.text_thread.observed(op.timestamp()))
944 .cloned()
945 .collect::<Vec<_>>();
946 context_ops.extend(self.pending_ops.iter().cloned());
947
948 cx.background_spawn(async move {
949 let buffer_ops = buffer_ops.await;
950 context_ops.sort_unstable_by_key(|op| op.timestamp());
951 buffer_ops
952 .into_iter()
953 .map(|op| proto::ContextOperation {
954 variant: Some(proto::context_operation::Variant::BufferOperation(
955 proto::context_operation::BufferOperation {
956 operation: Some(op),
957 },
958 )),
959 })
960 .chain(context_ops.into_iter().map(|op| op.to_proto()))
961 .collect()
962 })
963 }
964
965 pub fn apply_ops(
966 &mut self,
967 ops: impl IntoIterator<Item = TextThreadOperation>,
968 cx: &mut Context<Self>,
969 ) {
970 let mut buffer_ops = Vec::new();
971 for op in ops {
972 match op {
973 TextThreadOperation::BufferOperation(buffer_op) => buffer_ops.push(buffer_op),
974 op @ _ => self.pending_ops.push(op),
975 }
976 }
977 self.buffer
978 .update(cx, |buffer, cx| buffer.apply_ops(buffer_ops, cx));
979 self.flush_ops(cx);
980 }
981
982 fn flush_ops(&mut self, cx: &mut Context<TextThread>) {
983 let mut changed_messages = HashSet::default();
984 let mut summary_generated = false;
985
986 self.pending_ops.sort_unstable_by_key(|op| op.timestamp());
987 for op in mem::take(&mut self.pending_ops) {
988 if !self.can_apply_op(&op, cx) {
989 self.pending_ops.push(op);
990 continue;
991 }
992
993 let timestamp = op.timestamp();
994 match op.clone() {
995 TextThreadOperation::InsertMessage {
996 anchor, metadata, ..
997 } => {
998 if self.messages_metadata.contains_key(&anchor.id) {
999 // We already applied this operation.
1000 } else {
1001 changed_messages.insert(anchor.id);
1002 self.insert_message(anchor, metadata, cx);
1003 }
1004 }
1005 TextThreadOperation::UpdateMessage {
1006 message_id,
1007 metadata: new_metadata,
1008 ..
1009 } => {
1010 let metadata = self.messages_metadata.get_mut(&message_id).unwrap();
1011 if new_metadata.timestamp > metadata.timestamp {
1012 *metadata = new_metadata;
1013 changed_messages.insert(message_id);
1014 }
1015 }
1016 TextThreadOperation::UpdateSummary {
1017 summary: new_summary,
1018 ..
1019 } => {
1020 if self
1021 .summary
1022 .timestamp()
1023 .is_none_or(|current_timestamp| new_summary.timestamp > current_timestamp)
1024 {
1025 self.summary = TextThreadSummary::Content(new_summary);
1026 summary_generated = true;
1027 }
1028 }
1029 TextThreadOperation::SlashCommandStarted {
1030 id,
1031 output_range,
1032 name,
1033 ..
1034 } => {
1035 self.invoked_slash_commands.insert(
1036 id,
1037 InvokedSlashCommand {
1038 name: name.into(),
1039 range: output_range,
1040 run_commands_in_ranges: Vec::new(),
1041 status: InvokedSlashCommandStatus::Running(Task::ready(())),
1042 transaction: None,
1043 timestamp: id.0,
1044 },
1045 );
1046 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id: id });
1047 }
1048 TextThreadOperation::SlashCommandOutputSectionAdded { section, .. } => {
1049 let buffer = self.buffer.read(cx);
1050 if let Err(ix) = self
1051 .slash_command_output_sections
1052 .binary_search_by(|probe| probe.range.cmp(§ion.range, buffer))
1053 {
1054 self.slash_command_output_sections
1055 .insert(ix, section.clone());
1056 cx.emit(TextThreadEvent::SlashCommandOutputSectionAdded { section });
1057 }
1058 }
1059 TextThreadOperation::ThoughtProcessOutputSectionAdded { section, .. } => {
1060 let buffer = self.buffer.read(cx);
1061 if let Err(ix) = self
1062 .thought_process_output_sections
1063 .binary_search_by(|probe| probe.range.cmp(§ion.range, buffer))
1064 {
1065 self.thought_process_output_sections
1066 .insert(ix, section.clone());
1067 }
1068 }
1069 TextThreadOperation::SlashCommandFinished {
1070 id,
1071 error_message,
1072 timestamp,
1073 ..
1074 } => {
1075 if let Some(slash_command) = self.invoked_slash_commands.get_mut(&id)
1076 && timestamp > slash_command.timestamp
1077 {
1078 slash_command.timestamp = timestamp;
1079 match error_message {
1080 Some(message) => {
1081 slash_command.status =
1082 InvokedSlashCommandStatus::Error(message.into());
1083 }
1084 None => {
1085 slash_command.status = InvokedSlashCommandStatus::Finished;
1086 }
1087 }
1088 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id: id });
1089 }
1090 }
1091 TextThreadOperation::BufferOperation(_) => unreachable!(),
1092 }
1093
1094 self.version.observe(timestamp);
1095 self.timestamp.observe(timestamp);
1096 self.operations.push(op);
1097 }
1098
1099 if !changed_messages.is_empty() {
1100 self.message_roles_updated(changed_messages, cx);
1101 cx.emit(TextThreadEvent::MessagesEdited);
1102 cx.notify();
1103 }
1104
1105 if summary_generated {
1106 cx.emit(TextThreadEvent::SummaryChanged);
1107 cx.emit(TextThreadEvent::SummaryGenerated);
1108 cx.notify();
1109 }
1110 }
1111
1112 fn can_apply_op(&self, op: &TextThreadOperation, cx: &App) -> bool {
1113 if !self.version.observed_all(op.version()) {
1114 return false;
1115 }
1116
1117 match op {
1118 TextThreadOperation::InsertMessage { anchor, .. } => self
1119 .buffer
1120 .read(cx)
1121 .version
1122 .observed(anchor.start.timestamp),
1123 TextThreadOperation::UpdateMessage { message_id, .. } => {
1124 self.messages_metadata.contains_key(message_id)
1125 }
1126 TextThreadOperation::UpdateSummary { .. } => true,
1127 TextThreadOperation::SlashCommandStarted { output_range, .. } => {
1128 self.has_received_operations_for_anchor_range(output_range.clone(), cx)
1129 }
1130 TextThreadOperation::SlashCommandOutputSectionAdded { section, .. } => {
1131 self.has_received_operations_for_anchor_range(section.range.clone(), cx)
1132 }
1133 TextThreadOperation::ThoughtProcessOutputSectionAdded { section, .. } => {
1134 self.has_received_operations_for_anchor_range(section.range.clone(), cx)
1135 }
1136 TextThreadOperation::SlashCommandFinished { .. } => true,
1137 TextThreadOperation::BufferOperation(_) => {
1138 panic!("buffer operations should always be applied")
1139 }
1140 }
1141 }
1142
1143 fn has_received_operations_for_anchor_range(
1144 &self,
1145 range: Range<text::Anchor>,
1146 cx: &App,
1147 ) -> bool {
1148 let version = &self.buffer.read(cx).version;
1149 let observed_start = range.start == language::Anchor::MIN
1150 || range.start == language::Anchor::MAX
1151 || version.observed(range.start.timestamp);
1152 let observed_end = range.end == language::Anchor::MIN
1153 || range.end == language::Anchor::MAX
1154 || version.observed(range.end.timestamp);
1155 observed_start && observed_end
1156 }
1157
1158 fn push_op(&mut self, op: TextThreadOperation, cx: &mut Context<Self>) {
1159 self.operations.push(op.clone());
1160 cx.emit(TextThreadEvent::Operation(op));
1161 }
1162
1163 pub fn buffer(&self) -> &Entity<Buffer> {
1164 &self.buffer
1165 }
1166
1167 pub fn language_registry(&self) -> Arc<LanguageRegistry> {
1168 self.language_registry.clone()
1169 }
1170
1171 pub fn project(&self) -> Option<Entity<Project>> {
1172 self.project.clone()
1173 }
1174
1175 pub fn prompt_builder(&self) -> Arc<PromptBuilder> {
1176 self.prompt_builder.clone()
1177 }
1178
1179 pub fn path(&self) -> Option<&Arc<Path>> {
1180 self.path.as_ref()
1181 }
1182
1183 pub fn summary(&self) -> &TextThreadSummary {
1184 &self.summary
1185 }
1186
1187 pub fn parsed_slash_commands(&self) -> &[ParsedSlashCommand] {
1188 &self.parsed_slash_commands
1189 }
1190
1191 pub fn invoked_slash_command(
1192 &self,
1193 command_id: &InvokedSlashCommandId,
1194 ) -> Option<&InvokedSlashCommand> {
1195 self.invoked_slash_commands.get(command_id)
1196 }
1197
1198 pub fn slash_command_output_sections(&self) -> &[SlashCommandOutputSection<language::Anchor>] {
1199 &self.slash_command_output_sections
1200 }
1201
1202 pub fn thought_process_output_sections(
1203 &self,
1204 ) -> &[ThoughtProcessOutputSection<language::Anchor>] {
1205 &self.thought_process_output_sections
1206 }
1207
1208 pub fn contains_files(&self, cx: &App) -> bool {
1209 let buffer = self.buffer.read(cx);
1210 self.slash_command_output_sections.iter().any(|section| {
1211 section.is_valid(buffer)
1212 && section
1213 .metadata
1214 .as_ref()
1215 .and_then(|metadata| {
1216 serde_json::from_value::<FileCommandMetadata>(metadata.clone()).ok()
1217 })
1218 .is_some()
1219 })
1220 }
1221
1222 fn set_language(&mut self, cx: &mut Context<Self>) {
1223 let markdown = self.language_registry.language_for_name("Markdown");
1224 cx.spawn(async move |this, cx| {
1225 let markdown = markdown.await?;
1226 this.update(cx, |this, cx| {
1227 this.buffer
1228 .update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx));
1229 })
1230 })
1231 .detach_and_log_err(cx);
1232 }
1233
1234 fn handle_buffer_event(
1235 &mut self,
1236 _: Entity<Buffer>,
1237 event: &language::BufferEvent,
1238 cx: &mut Context<Self>,
1239 ) {
1240 match event {
1241 language::BufferEvent::Operation {
1242 operation,
1243 is_local: true,
1244 } => cx.emit(TextThreadEvent::Operation(
1245 TextThreadOperation::BufferOperation(operation.clone()),
1246 )),
1247 language::BufferEvent::Edited => {
1248 self.count_remaining_tokens(cx);
1249 self.reparse(cx);
1250 cx.emit(TextThreadEvent::MessagesEdited);
1251 }
1252 _ => {}
1253 }
1254 }
1255
1256 pub fn token_count(&self) -> Option<u64> {
1257 self.token_count
1258 }
1259
1260 pub(crate) fn count_remaining_tokens(&mut self, cx: &mut Context<Self>) {
1261 // Assume it will be a Chat request, even though that takes fewer tokens (and risks going over the limit),
1262 // because otherwise you see in the UI that your empty message has a bunch of tokens already used.
1263 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1264 return;
1265 };
1266 let request = self.to_completion_request(Some(&model.model), cx);
1267 let debounce = self.token_count.is_some();
1268 self.pending_token_count = cx.spawn(async move |this, cx| {
1269 async move {
1270 if debounce {
1271 cx.background_executor()
1272 .timer(Duration::from_millis(200))
1273 .await;
1274 }
1275
1276 let token_count = cx
1277 .update(|cx| model.model.count_tokens(request, cx))?
1278 .await?;
1279 this.update(cx, |this, cx| {
1280 this.token_count = Some(token_count);
1281 this.start_cache_warming(&model.model, cx);
1282 cx.notify()
1283 })
1284 }
1285 .log_err()
1286 .await
1287 });
1288 }
1289
1290 pub fn mark_cache_anchors(
1291 &mut self,
1292 cache_configuration: &Option<LanguageModelCacheConfiguration>,
1293 speculative: bool,
1294 cx: &mut Context<Self>,
1295 ) -> bool {
1296 let cache_configuration =
1297 cache_configuration
1298 .as_ref()
1299 .unwrap_or(&LanguageModelCacheConfiguration {
1300 max_cache_anchors: 0,
1301 should_speculate: false,
1302 min_total_token: 0,
1303 });
1304
1305 let messages: Vec<Message> = self.messages(cx).collect();
1306
1307 let mut sorted_messages = messages.clone();
1308 if speculative {
1309 // Avoid caching the last message if this is a speculative cache fetch as
1310 // it's likely to change.
1311 sorted_messages.pop();
1312 }
1313 sorted_messages.retain(|m| m.role == Role::User);
1314 sorted_messages.sort_by(|a, b| b.offset_range.len().cmp(&a.offset_range.len()));
1315
1316 let cache_anchors = if self.token_count.unwrap_or(0) < cache_configuration.min_total_token {
1317 // If we have't hit the minimum threshold to enable caching, don't cache anything.
1318 0
1319 } else {
1320 // Save 1 anchor for the inline assistant to use.
1321 max(cache_configuration.max_cache_anchors, 1) - 1
1322 };
1323 sorted_messages.truncate(cache_anchors);
1324
1325 let anchors: HashSet<MessageId> = sorted_messages
1326 .into_iter()
1327 .map(|message| message.id)
1328 .collect();
1329
1330 let buffer = self.buffer.read(cx).snapshot();
1331 let invalidated_caches: HashSet<MessageId> = messages
1332 .iter()
1333 .scan(false, |encountered_invalid, message| {
1334 let message_id = message.id;
1335 let is_invalid = self
1336 .messages_metadata
1337 .get(&message_id)
1338 .is_none_or(|metadata| {
1339 !metadata.is_cache_valid(&buffer, &message.offset_range)
1340 || *encountered_invalid
1341 });
1342 *encountered_invalid |= is_invalid;
1343 Some(if is_invalid { Some(message_id) } else { None })
1344 })
1345 .flatten()
1346 .collect();
1347
1348 let last_anchor = messages.iter().rev().find_map(|message| {
1349 if anchors.contains(&message.id) {
1350 Some(message.id)
1351 } else {
1352 None
1353 }
1354 });
1355
1356 let mut new_anchor_needs_caching = false;
1357 let current_version = &buffer.version;
1358 // If we have no anchors, mark all messages as not being cached.
1359 let mut hit_last_anchor = last_anchor.is_none();
1360
1361 for message in messages.iter() {
1362 if hit_last_anchor {
1363 self.update_metadata(message.id, cx, |metadata| metadata.cache = None);
1364 continue;
1365 }
1366
1367 if let Some(last_anchor) = last_anchor
1368 && message.id == last_anchor
1369 {
1370 hit_last_anchor = true;
1371 }
1372
1373 new_anchor_needs_caching = new_anchor_needs_caching
1374 || (invalidated_caches.contains(&message.id) && anchors.contains(&message.id));
1375
1376 self.update_metadata(message.id, cx, |metadata| {
1377 let cache_status = if invalidated_caches.contains(&message.id) {
1378 CacheStatus::Pending
1379 } else {
1380 metadata
1381 .cache
1382 .as_ref()
1383 .map_or(CacheStatus::Pending, |cm| cm.status.clone())
1384 };
1385 metadata.cache = Some(MessageCacheMetadata {
1386 is_anchor: anchors.contains(&message.id),
1387 is_final_anchor: hit_last_anchor,
1388 status: cache_status,
1389 cached_at: current_version.clone(),
1390 });
1391 });
1392 }
1393 new_anchor_needs_caching
1394 }
1395
1396 fn start_cache_warming(&mut self, model: &Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1397 let cache_configuration = model.cache_configuration();
1398
1399 if !self.mark_cache_anchors(&cache_configuration, true, cx) {
1400 return;
1401 }
1402 if !self.pending_completions.is_empty() {
1403 return;
1404 }
1405 if let Some(cache_configuration) = cache_configuration
1406 && !cache_configuration.should_speculate
1407 {
1408 return;
1409 }
1410
1411 let request = {
1412 let mut req = self.to_completion_request(Some(model), cx);
1413 // Skip the last message because it's likely to change and
1414 // therefore would be a waste to cache.
1415 req.messages.pop();
1416 req.messages.push(LanguageModelRequestMessage {
1417 role: Role::User,
1418 content: vec!["Respond only with OK, nothing else.".into()],
1419 cache: false,
1420 });
1421 req
1422 };
1423
1424 let model = Arc::clone(model);
1425 self.pending_cache_warming_task = cx.spawn(async move |this, cx| {
1426 async move {
1427 match model.stream_completion(request, cx).await {
1428 Ok(mut stream) => {
1429 stream.next().await;
1430 log::info!("Cache warming completed successfully");
1431 }
1432 Err(e) => {
1433 log::warn!("Cache warming failed: {}", e);
1434 }
1435 };
1436 this.update(cx, |this, cx| {
1437 this.update_cache_status_for_completion(cx);
1438 })
1439 .ok();
1440 anyhow::Ok(())
1441 }
1442 .log_err()
1443 .await
1444 });
1445 }
1446
1447 pub fn update_cache_status_for_completion(&mut self, cx: &mut Context<Self>) {
1448 let cached_message_ids: Vec<MessageId> = self
1449 .messages_metadata
1450 .iter()
1451 .filter_map(|(message_id, metadata)| {
1452 metadata.cache.as_ref().and_then(|cache| {
1453 if cache.status == CacheStatus::Pending {
1454 Some(*message_id)
1455 } else {
1456 None
1457 }
1458 })
1459 })
1460 .collect();
1461
1462 for message_id in cached_message_ids {
1463 self.update_metadata(message_id, cx, |metadata| {
1464 if let Some(cache) = &mut metadata.cache {
1465 cache.status = CacheStatus::Cached;
1466 }
1467 });
1468 }
1469 cx.notify();
1470 }
1471
1472 pub fn reparse(&mut self, cx: &mut Context<Self>) {
1473 let buffer = self.buffer.read(cx).text_snapshot();
1474 let mut row_ranges = self
1475 .edits_since_last_parse
1476 .consume()
1477 .into_iter()
1478 .map(|edit| {
1479 let start_row = buffer.offset_to_point(edit.new.start).row;
1480 let end_row = buffer.offset_to_point(edit.new.end).row + 1;
1481 start_row..end_row
1482 })
1483 .peekable();
1484
1485 let mut removed_parsed_slash_command_ranges = Vec::new();
1486 let mut updated_parsed_slash_commands = Vec::new();
1487 while let Some(mut row_range) = row_ranges.next() {
1488 while let Some(next_row_range) = row_ranges.peek() {
1489 if row_range.end >= next_row_range.start {
1490 row_range.end = next_row_range.end;
1491 row_ranges.next();
1492 } else {
1493 break;
1494 }
1495 }
1496
1497 let start = buffer.anchor_before(Point::new(row_range.start, 0));
1498 let end = buffer.anchor_after(Point::new(
1499 row_range.end - 1,
1500 buffer.line_len(row_range.end - 1),
1501 ));
1502
1503 self.reparse_slash_commands_in_range(
1504 start..end,
1505 &buffer,
1506 &mut updated_parsed_slash_commands,
1507 &mut removed_parsed_slash_command_ranges,
1508 cx,
1509 );
1510 self.invalidate_pending_slash_commands(&buffer, cx);
1511 }
1512
1513 if !updated_parsed_slash_commands.is_empty()
1514 || !removed_parsed_slash_command_ranges.is_empty()
1515 {
1516 cx.emit(TextThreadEvent::ParsedSlashCommandsUpdated {
1517 removed: removed_parsed_slash_command_ranges,
1518 updated: updated_parsed_slash_commands,
1519 });
1520 }
1521 }
1522
1523 fn reparse_slash_commands_in_range(
1524 &mut self,
1525 range: Range<text::Anchor>,
1526 buffer: &BufferSnapshot,
1527 updated: &mut Vec<ParsedSlashCommand>,
1528 removed: &mut Vec<Range<text::Anchor>>,
1529 cx: &App,
1530 ) {
1531 let old_range = self.pending_command_indices_for_range(range.clone(), cx);
1532
1533 let mut new_commands = Vec::new();
1534 let mut lines = buffer.text_for_range(range).lines();
1535 let mut offset = lines.offset();
1536 while let Some(line) = lines.next() {
1537 if let Some(command_line) = SlashCommandLine::parse(line) {
1538 let name = &line[command_line.name.clone()];
1539 let arguments = command_line
1540 .arguments
1541 .iter()
1542 .filter_map(|argument_range| {
1543 if argument_range.is_empty() {
1544 None
1545 } else {
1546 line.get(argument_range.clone())
1547 }
1548 })
1549 .map(ToOwned::to_owned)
1550 .collect::<SmallVec<_>>();
1551 if let Some(command) = self.slash_commands.command(name, cx)
1552 && (!command.requires_argument() || !arguments.is_empty())
1553 {
1554 let start_ix = offset + command_line.name.start - 1;
1555 let end_ix = offset
1556 + command_line
1557 .arguments
1558 .last()
1559 .map_or(command_line.name.end, |argument| argument.end);
1560 let source_range = buffer.anchor_after(start_ix)..buffer.anchor_after(end_ix);
1561 let pending_command = ParsedSlashCommand {
1562 name: name.to_string(),
1563 arguments,
1564 source_range,
1565 status: PendingSlashCommandStatus::Idle,
1566 };
1567 updated.push(pending_command.clone());
1568 new_commands.push(pending_command);
1569 }
1570 }
1571
1572 offset = lines.offset();
1573 }
1574
1575 let removed_commands = self.parsed_slash_commands.splice(old_range, new_commands);
1576 removed.extend(removed_commands.map(|command| command.source_range));
1577 }
1578
1579 fn invalidate_pending_slash_commands(
1580 &mut self,
1581 buffer: &BufferSnapshot,
1582 cx: &mut Context<Self>,
1583 ) {
1584 let mut invalidated_command_ids = Vec::new();
1585 for (&command_id, command) in self.invoked_slash_commands.iter_mut() {
1586 if !matches!(command.status, InvokedSlashCommandStatus::Finished)
1587 && (!command.range.start.is_valid(buffer) || !command.range.end.is_valid(buffer))
1588 {
1589 command.status = InvokedSlashCommandStatus::Finished;
1590 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1591 invalidated_command_ids.push(command_id);
1592 }
1593 }
1594
1595 for command_id in invalidated_command_ids {
1596 let version = self.version.clone();
1597 let timestamp = self.next_timestamp();
1598 self.push_op(
1599 TextThreadOperation::SlashCommandFinished {
1600 id: command_id,
1601 timestamp,
1602 error_message: None,
1603 version: version.clone(),
1604 },
1605 cx,
1606 );
1607 }
1608 }
1609
1610 pub fn pending_command_for_position(
1611 &mut self,
1612 position: language::Anchor,
1613 cx: &mut Context<Self>,
1614 ) -> Option<&mut ParsedSlashCommand> {
1615 let buffer = self.buffer.read(cx);
1616 match self
1617 .parsed_slash_commands
1618 .binary_search_by(|probe| probe.source_range.end.cmp(&position, buffer))
1619 {
1620 Ok(ix) => Some(&mut self.parsed_slash_commands[ix]),
1621 Err(ix) => {
1622 let cmd = self.parsed_slash_commands.get_mut(ix)?;
1623 if position.cmp(&cmd.source_range.start, buffer).is_ge()
1624 && position.cmp(&cmd.source_range.end, buffer).is_le()
1625 {
1626 Some(cmd)
1627 } else {
1628 None
1629 }
1630 }
1631 }
1632 }
1633
1634 pub fn pending_commands_for_range(
1635 &self,
1636 range: Range<language::Anchor>,
1637 cx: &App,
1638 ) -> &[ParsedSlashCommand] {
1639 let range = self.pending_command_indices_for_range(range, cx);
1640 &self.parsed_slash_commands[range]
1641 }
1642
1643 fn pending_command_indices_for_range(
1644 &self,
1645 range: Range<language::Anchor>,
1646 cx: &App,
1647 ) -> Range<usize> {
1648 self.indices_intersecting_buffer_range(&self.parsed_slash_commands, range, cx)
1649 }
1650
1651 fn indices_intersecting_buffer_range<T: ContextAnnotation>(
1652 &self,
1653 all_annotations: &[T],
1654 range: Range<language::Anchor>,
1655 cx: &App,
1656 ) -> Range<usize> {
1657 let buffer = self.buffer.read(cx);
1658 let start_ix = match all_annotations
1659 .binary_search_by(|probe| probe.range().end.cmp(&range.start, buffer))
1660 {
1661 Ok(ix) | Err(ix) => ix,
1662 };
1663 let end_ix = match all_annotations
1664 .binary_search_by(|probe| probe.range().start.cmp(&range.end, buffer))
1665 {
1666 Ok(ix) => ix + 1,
1667 Err(ix) => ix,
1668 };
1669 start_ix..end_ix
1670 }
1671
1672 pub fn insert_command_output(
1673 &mut self,
1674 command_source_range: Range<language::Anchor>,
1675 name: &str,
1676 output: Task<SlashCommandResult>,
1677 ensure_trailing_newline: bool,
1678 cx: &mut Context<Self>,
1679 ) {
1680 let version = self.version.clone();
1681 let command_id = InvokedSlashCommandId(self.next_timestamp());
1682
1683 const PENDING_OUTPUT_END_MARKER: &str = "…";
1684
1685 let (command_range, command_source_range, insert_position, first_transaction) =
1686 self.buffer.update(cx, |buffer, cx| {
1687 let command_source_range = command_source_range.to_offset(buffer);
1688 let mut insertion = format!("\n{PENDING_OUTPUT_END_MARKER}");
1689 if ensure_trailing_newline {
1690 insertion.push('\n');
1691 }
1692
1693 buffer.finalize_last_transaction();
1694 buffer.start_transaction();
1695 buffer.edit(
1696 [(
1697 command_source_range.end..command_source_range.end,
1698 insertion,
1699 )],
1700 None,
1701 cx,
1702 );
1703 let first_transaction = buffer.end_transaction(cx).unwrap();
1704 buffer.finalize_last_transaction();
1705
1706 let insert_position = buffer.anchor_after(command_source_range.end + 1);
1707 let command_range = buffer.anchor_after(command_source_range.start)
1708 ..buffer.anchor_before(
1709 command_source_range.end + 1 + PENDING_OUTPUT_END_MARKER.len(),
1710 );
1711 let command_source_range = buffer.anchor_before(command_source_range.start)
1712 ..buffer.anchor_before(command_source_range.end + 1);
1713 (
1714 command_range,
1715 command_source_range,
1716 insert_position,
1717 first_transaction,
1718 )
1719 });
1720 self.reparse(cx);
1721
1722 let insert_output_task = cx.spawn(async move |this, cx| {
1723 let run_command = async {
1724 let mut stream = output.await?;
1725
1726 struct PendingSection {
1727 start: language::Anchor,
1728 icon: IconName,
1729 label: SharedString,
1730 metadata: Option<serde_json::Value>,
1731 }
1732
1733 let mut pending_section_stack: Vec<PendingSection> = Vec::new();
1734 let mut last_role: Option<Role> = None;
1735 let mut last_section_range = None;
1736
1737 while let Some(event) = stream.next().await {
1738 let event = event?;
1739 this.update(cx, |this, cx| {
1740 this.buffer.update(cx, |buffer, _cx| {
1741 buffer.finalize_last_transaction();
1742 buffer.start_transaction()
1743 });
1744
1745 match event {
1746 SlashCommandEvent::StartMessage {
1747 role,
1748 merge_same_roles,
1749 } => {
1750 if !merge_same_roles && Some(role) != last_role {
1751 let buffer = this.buffer.read(cx);
1752 let offset = insert_position.to_offset(buffer);
1753 this.insert_message_at_offset(
1754 offset,
1755 role,
1756 MessageStatus::Pending,
1757 cx,
1758 );
1759 }
1760
1761 last_role = Some(role);
1762 }
1763 SlashCommandEvent::StartSection {
1764 icon,
1765 label,
1766 metadata,
1767 } => {
1768 this.buffer.update(cx, |buffer, cx| {
1769 let insert_point = insert_position.to_point(buffer);
1770 if insert_point.column > 0 {
1771 buffer.edit([(insert_point..insert_point, "\n")], None, cx);
1772 }
1773
1774 pending_section_stack.push(PendingSection {
1775 start: buffer.anchor_before(insert_position),
1776 icon,
1777 label,
1778 metadata,
1779 });
1780 });
1781 }
1782 SlashCommandEvent::Content(SlashCommandContent::Text {
1783 text,
1784 run_commands_in_text,
1785 }) => {
1786 let start = this.buffer.read(cx).anchor_before(insert_position);
1787
1788 this.buffer.update(cx, |buffer, cx| {
1789 buffer.edit(
1790 [(insert_position..insert_position, text)],
1791 None,
1792 cx,
1793 )
1794 });
1795
1796 let end = this.buffer.read(cx).anchor_before(insert_position);
1797 if run_commands_in_text
1798 && let Some(invoked_slash_command) =
1799 this.invoked_slash_commands.get_mut(&command_id)
1800 {
1801 invoked_slash_command
1802 .run_commands_in_ranges
1803 .push(start..end);
1804 }
1805 }
1806 SlashCommandEvent::EndSection => {
1807 if let Some(pending_section) = pending_section_stack.pop() {
1808 let offset_range = (pending_section.start..insert_position)
1809 .to_offset(this.buffer.read(cx));
1810 if !offset_range.is_empty() {
1811 let range = this.buffer.update(cx, |buffer, _cx| {
1812 buffer.anchor_after(offset_range.start)
1813 ..buffer.anchor_before(offset_range.end)
1814 });
1815 this.insert_slash_command_output_section(
1816 SlashCommandOutputSection {
1817 range: range.clone(),
1818 icon: pending_section.icon,
1819 label: pending_section.label,
1820 metadata: pending_section.metadata,
1821 },
1822 cx,
1823 );
1824 last_section_range = Some(range);
1825 }
1826 }
1827 }
1828 }
1829
1830 this.buffer.update(cx, |buffer, cx| {
1831 if let Some(event_transaction) = buffer.end_transaction(cx) {
1832 buffer.merge_transactions(event_transaction, first_transaction);
1833 }
1834 });
1835 })?;
1836 }
1837
1838 this.update(cx, |this, cx| {
1839 this.buffer.update(cx, |buffer, cx| {
1840 buffer.finalize_last_transaction();
1841 buffer.start_transaction();
1842
1843 let mut deletions = vec![(command_source_range.to_offset(buffer), "")];
1844 let insert_position = insert_position.to_offset(buffer);
1845 let command_range_end = command_range.end.to_offset(buffer);
1846
1847 if buffer.contains_str_at(insert_position, PENDING_OUTPUT_END_MARKER) {
1848 deletions.push((
1849 insert_position..insert_position + PENDING_OUTPUT_END_MARKER.len(),
1850 "",
1851 ));
1852 }
1853
1854 if ensure_trailing_newline
1855 && buffer.contains_str_at(command_range_end, "\n")
1856 {
1857 let newline_offset = insert_position.saturating_sub(1);
1858 if buffer.contains_str_at(newline_offset, "\n")
1859 && last_section_range.is_none_or(|last_section_range| {
1860 !last_section_range
1861 .to_offset(buffer)
1862 .contains(&newline_offset)
1863 })
1864 {
1865 deletions.push((command_range_end..command_range_end + 1, ""));
1866 }
1867 }
1868
1869 buffer.edit(deletions, None, cx);
1870
1871 if let Some(deletion_transaction) = buffer.end_transaction(cx) {
1872 buffer.merge_transactions(deletion_transaction, first_transaction);
1873 }
1874 });
1875 })?;
1876
1877 debug_assert!(pending_section_stack.is_empty());
1878
1879 anyhow::Ok(())
1880 };
1881
1882 let command_result = run_command.await;
1883
1884 this.update(cx, |this, cx| {
1885 let version = this.version.clone();
1886 let timestamp = this.next_timestamp();
1887 let Some(invoked_slash_command) = this.invoked_slash_commands.get_mut(&command_id)
1888 else {
1889 return;
1890 };
1891 let mut error_message = None;
1892 match command_result {
1893 Ok(()) => {
1894 invoked_slash_command.status = InvokedSlashCommandStatus::Finished;
1895 }
1896 Err(error) => {
1897 let message = error.to_string();
1898 invoked_slash_command.status =
1899 InvokedSlashCommandStatus::Error(message.clone().into());
1900 error_message = Some(message);
1901 }
1902 }
1903
1904 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1905 this.push_op(
1906 TextThreadOperation::SlashCommandFinished {
1907 id: command_id,
1908 timestamp,
1909 error_message,
1910 version,
1911 },
1912 cx,
1913 );
1914 })
1915 .ok();
1916 });
1917
1918 self.invoked_slash_commands.insert(
1919 command_id,
1920 InvokedSlashCommand {
1921 name: name.to_string().into(),
1922 range: command_range.clone(),
1923 run_commands_in_ranges: Vec::new(),
1924 status: InvokedSlashCommandStatus::Running(insert_output_task),
1925 transaction: Some(first_transaction),
1926 timestamp: command_id.0,
1927 },
1928 );
1929 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1930 self.push_op(
1931 TextThreadOperation::SlashCommandStarted {
1932 id: command_id,
1933 output_range: command_range,
1934 name: name.to_string(),
1935 version,
1936 },
1937 cx,
1938 );
1939 }
1940
1941 fn insert_slash_command_output_section(
1942 &mut self,
1943 section: SlashCommandOutputSection<language::Anchor>,
1944 cx: &mut Context<Self>,
1945 ) {
1946 let buffer = self.buffer.read(cx);
1947 let insertion_ix = match self
1948 .slash_command_output_sections
1949 .binary_search_by(|probe| probe.range.cmp(§ion.range, buffer))
1950 {
1951 Ok(ix) | Err(ix) => ix,
1952 };
1953 self.slash_command_output_sections
1954 .insert(insertion_ix, section.clone());
1955 cx.emit(TextThreadEvent::SlashCommandOutputSectionAdded {
1956 section: section.clone(),
1957 });
1958 let version = self.version.clone();
1959 let timestamp = self.next_timestamp();
1960 self.push_op(
1961 TextThreadOperation::SlashCommandOutputSectionAdded {
1962 timestamp,
1963 section,
1964 version,
1965 },
1966 cx,
1967 );
1968 }
1969
1970 fn insert_thought_process_output_section(
1971 &mut self,
1972 section: ThoughtProcessOutputSection<language::Anchor>,
1973 cx: &mut Context<Self>,
1974 ) {
1975 let buffer = self.buffer.read(cx);
1976 let insertion_ix = match self
1977 .thought_process_output_sections
1978 .binary_search_by(|probe| probe.range.cmp(§ion.range, buffer))
1979 {
1980 Ok(ix) | Err(ix) => ix,
1981 };
1982 self.thought_process_output_sections
1983 .insert(insertion_ix, section.clone());
1984 // cx.emit(ContextEvent::ThoughtProcessOutputSectionAdded {
1985 // section: section.clone(),
1986 // });
1987 let version = self.version.clone();
1988 let timestamp = self.next_timestamp();
1989 self.push_op(
1990 TextThreadOperation::ThoughtProcessOutputSectionAdded {
1991 timestamp,
1992 section,
1993 version,
1994 },
1995 cx,
1996 );
1997 }
1998
1999 pub fn completion_provider_changed(&mut self, cx: &mut Context<Self>) {
2000 self.count_remaining_tokens(cx);
2001 }
2002
2003 fn get_last_valid_message_id(&self, cx: &Context<Self>) -> Option<MessageId> {
2004 self.message_anchors.iter().rev().find_map(|message| {
2005 message
2006 .start
2007 .is_valid(self.buffer.read(cx))
2008 .then_some(message.id)
2009 })
2010 }
2011
2012 pub fn assist(&mut self, cx: &mut Context<Self>) -> Option<MessageAnchor> {
2013 let model_registry = LanguageModelRegistry::read_global(cx);
2014 let model = model_registry.default_model()?;
2015 let last_message_id = self.get_last_valid_message_id(cx)?;
2016
2017 if !model.provider.is_authenticated(cx) {
2018 log::info!("completion provider has no credentials");
2019 return None;
2020 }
2021
2022 let model = model.model;
2023
2024 // Compute which messages to cache, including the last one.
2025 self.mark_cache_anchors(&model.cache_configuration(), false, cx);
2026
2027 let request = self.to_completion_request(Some(&model), cx);
2028
2029 let assistant_message = self
2030 .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
2031 .unwrap();
2032
2033 // Queue up the user's next reply.
2034 let user_message = self
2035 .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
2036 .unwrap();
2037
2038 let pending_completion_id = post_inc(&mut self.completion_count);
2039
2040 let task = cx.spawn({
2041 async move |this, cx| {
2042 let stream = model.stream_completion(request, cx);
2043 let assistant_message_id = assistant_message.id;
2044 let mut response_latency = None;
2045 let stream_completion = async {
2046 let request_start = Instant::now();
2047 let mut events = stream.await?;
2048 let mut stop_reason = StopReason::EndTurn;
2049 let mut thought_process_stack = Vec::new();
2050
2051 const THOUGHT_PROCESS_START_MARKER: &str = "<think>\n";
2052 const THOUGHT_PROCESS_END_MARKER: &str = "\n</think>";
2053
2054 while let Some(event) = events.next().await {
2055 if response_latency.is_none() {
2056 response_latency = Some(request_start.elapsed());
2057 }
2058 let event = event?;
2059
2060 let mut context_event = None;
2061 let mut thought_process_output_section = None;
2062
2063 this.update(cx, |this, cx| {
2064 let message_ix = this
2065 .message_anchors
2066 .iter()
2067 .position(|message| message.id == assistant_message_id)?;
2068 this.buffer.update(cx, |buffer, cx| {
2069 let message_old_end_offset = this.message_anchors[message_ix + 1..]
2070 .iter()
2071 .find(|message| message.start.is_valid(buffer))
2072 .map_or(buffer.len(), |message| {
2073 message.start.to_offset(buffer).saturating_sub(1)
2074 });
2075
2076 match event {
2077 LanguageModelCompletionEvent::StatusUpdate(status_update) => {
2078 if let CompletionRequestStatus::UsageUpdated { amount, limit } = status_update {
2079 this.update_model_request_usage(
2080 amount as u32,
2081 limit,
2082 cx,
2083 );
2084 }
2085 }
2086 LanguageModelCompletionEvent::StartMessage { .. } => {}
2087 LanguageModelCompletionEvent::Stop(reason) => {
2088 stop_reason = reason;
2089 }
2090 LanguageModelCompletionEvent::Thinking { text: chunk, .. } => {
2091 if thought_process_stack.is_empty() {
2092 let start =
2093 buffer.anchor_before(message_old_end_offset);
2094 thought_process_stack.push(start);
2095 let chunk =
2096 format!("{THOUGHT_PROCESS_START_MARKER}{chunk}{THOUGHT_PROCESS_END_MARKER}");
2097 let chunk_len = chunk.len();
2098 buffer.edit(
2099 [(
2100 message_old_end_offset..message_old_end_offset,
2101 chunk,
2102 )],
2103 None,
2104 cx,
2105 );
2106 let end = buffer
2107 .anchor_before(message_old_end_offset + chunk_len);
2108 context_event = Some(
2109 TextThreadEvent::StartedThoughtProcess(start..end),
2110 );
2111 } else {
2112 // This ensures that all the thinking chunks are inserted inside the thinking tag
2113 let insertion_position =
2114 message_old_end_offset - THOUGHT_PROCESS_END_MARKER.len();
2115 buffer.edit(
2116 [(insertion_position..insertion_position, chunk)],
2117 None,
2118 cx,
2119 );
2120 }
2121 }
2122 LanguageModelCompletionEvent::RedactedThinking { .. } => {},
2123 LanguageModelCompletionEvent::Text(mut chunk) => {
2124 if let Some(start) = thought_process_stack.pop() {
2125 let end = buffer.anchor_before(message_old_end_offset);
2126 context_event =
2127 Some(TextThreadEvent::EndedThoughtProcess(end));
2128 thought_process_output_section =
2129 Some(ThoughtProcessOutputSection {
2130 range: start..end,
2131 });
2132 chunk.insert_str(0, "\n\n");
2133 }
2134
2135 buffer.edit(
2136 [(
2137 message_old_end_offset..message_old_end_offset,
2138 chunk,
2139 )],
2140 None,
2141 cx,
2142 );
2143 }
2144 LanguageModelCompletionEvent::ToolUse(_) |
2145 LanguageModelCompletionEvent::ToolUseJsonParseError { .. } |
2146 LanguageModelCompletionEvent::UsageUpdate(_) => {}
2147 }
2148 });
2149
2150 if let Some(section) = thought_process_output_section.take() {
2151 this.insert_thought_process_output_section(section, cx);
2152 }
2153 if let Some(context_event) = context_event.take() {
2154 cx.emit(context_event);
2155 }
2156
2157 cx.emit(TextThreadEvent::StreamedCompletion);
2158
2159 Some(())
2160 })?;
2161 smol::future::yield_now().await;
2162 }
2163 this.update(cx, |this, cx| {
2164 this.pending_completions
2165 .retain(|completion| completion.id != pending_completion_id);
2166 this.summarize(false, cx);
2167 this.update_cache_status_for_completion(cx);
2168 })?;
2169
2170 anyhow::Ok(stop_reason)
2171 };
2172
2173 let result = stream_completion.await;
2174
2175 this.update(cx, |this, cx| {
2176 let error_message = if let Some(error) = result.as_ref().err() {
2177 if error.is::<PaymentRequiredError>() {
2178 cx.emit(TextThreadEvent::ShowPaymentRequiredError);
2179 this.update_metadata(assistant_message_id, cx, |metadata| {
2180 metadata.status = MessageStatus::Canceled;
2181 });
2182 Some(error.to_string())
2183 } else {
2184 let error_message = error
2185 .chain()
2186 .map(|err| err.to_string())
2187 .collect::<Vec<_>>()
2188 .join("\n");
2189 cx.emit(TextThreadEvent::ShowAssistError(SharedString::from(
2190 error_message.clone(),
2191 )));
2192 this.update_metadata(assistant_message_id, cx, |metadata| {
2193 metadata.status =
2194 MessageStatus::Error(SharedString::from(error_message.clone()));
2195 });
2196 Some(error_message)
2197 }
2198 } else {
2199 this.update_metadata(assistant_message_id, cx, |metadata| {
2200 metadata.status = MessageStatus::Done;
2201 });
2202 None
2203 };
2204
2205 let language_name = this
2206 .buffer
2207 .read(cx)
2208 .language()
2209 .map(|language| language.name());
2210 report_assistant_event(
2211 AssistantEventData {
2212 conversation_id: Some(this.id.0.clone()),
2213 kind: AssistantKind::Panel,
2214 phase: AssistantPhase::Response,
2215 message_id: None,
2216 model: model.telemetry_id(),
2217 model_provider: model.provider_id().to_string(),
2218 response_latency,
2219 error_message,
2220 language_name: language_name.map(|name| name.to_proto()),
2221 },
2222 this.telemetry.clone(),
2223 cx.http_client(),
2224 model.api_key(cx),
2225 cx.background_executor(),
2226 );
2227
2228 if let Ok(stop_reason) = result {
2229 match stop_reason {
2230 StopReason::ToolUse => {}
2231 StopReason::EndTurn => {}
2232 StopReason::MaxTokens => {}
2233 StopReason::Refusal => {}
2234 }
2235 }
2236 })
2237 .ok();
2238 }
2239 });
2240
2241 self.pending_completions.push(PendingCompletion {
2242 id: pending_completion_id,
2243 assistant_message_id: assistant_message.id,
2244 _task: task,
2245 });
2246
2247 Some(user_message)
2248 }
2249
2250 pub fn to_xml(&self, cx: &App) -> String {
2251 let mut output = String::new();
2252 let buffer = self.buffer.read(cx);
2253 for message in self.messages(cx) {
2254 if message.status != MessageStatus::Done {
2255 continue;
2256 }
2257
2258 writeln!(&mut output, "<{}>", message.role).unwrap();
2259 for chunk in buffer.text_for_range(message.offset_range) {
2260 output.push_str(chunk);
2261 }
2262 if !output.ends_with('\n') {
2263 output.push('\n');
2264 }
2265 writeln!(&mut output, "</{}>", message.role).unwrap();
2266 }
2267 output
2268 }
2269
2270 pub fn to_completion_request(
2271 &self,
2272 model: Option<&Arc<dyn LanguageModel>>,
2273 cx: &App,
2274 ) -> LanguageModelRequest {
2275 let buffer = self.buffer.read(cx);
2276
2277 let mut contents = self.contents(cx).peekable();
2278
2279 fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2280 let text: String = buffer.text_for_range(range).collect();
2281 if text.trim().is_empty() {
2282 None
2283 } else {
2284 Some(text)
2285 }
2286 }
2287
2288 let mut completion_request = LanguageModelRequest {
2289 thread_id: None,
2290 prompt_id: None,
2291 intent: Some(CompletionIntent::UserPrompt),
2292 mode: None,
2293 messages: Vec::new(),
2294 tools: Vec::new(),
2295 tool_choice: None,
2296 stop: Vec::new(),
2297 temperature: model.and_then(|model| AgentSettings::temperature_for_model(model, cx)),
2298 thinking_allowed: true,
2299 };
2300 for message in self.messages(cx) {
2301 if message.status != MessageStatus::Done {
2302 continue;
2303 }
2304
2305 let mut offset = message.offset_range.start;
2306 let mut request_message = LanguageModelRequestMessage {
2307 role: message.role,
2308 content: Vec::new(),
2309 cache: message.cache.as_ref().is_some_and(|cache| cache.is_anchor),
2310 };
2311
2312 while let Some(content) = contents.peek() {
2313 if content
2314 .range()
2315 .end
2316 .cmp(&message.anchor_range.end, buffer)
2317 .is_lt()
2318 {
2319 let content = contents.next().unwrap();
2320 let range = content.range().to_offset(buffer);
2321 request_message.content.extend(
2322 collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2323 );
2324
2325 match content {
2326 Content::Image { image, .. } => {
2327 if let Some(image) = image.clone().now_or_never().flatten() {
2328 request_message
2329 .content
2330 .push(language_model::MessageContent::Image(image));
2331 }
2332 }
2333 }
2334
2335 offset = range.end;
2336 } else {
2337 break;
2338 }
2339 }
2340
2341 request_message.content.extend(
2342 collect_text_content(buffer, offset..message.offset_range.end)
2343 .map(MessageContent::Text),
2344 );
2345
2346 if !request_message.contents_empty() {
2347 completion_request.messages.push(request_message);
2348 }
2349 }
2350 let supports_burn_mode = if let Some(model) = model {
2351 model.supports_burn_mode()
2352 } else {
2353 false
2354 };
2355
2356 if supports_burn_mode {
2357 completion_request.mode = Some(self.completion_mode.into());
2358 }
2359 completion_request
2360 }
2361
2362 pub fn cancel_last_assist(&mut self, cx: &mut Context<Self>) -> bool {
2363 if let Some(pending_completion) = self.pending_completions.pop() {
2364 self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2365 if metadata.status == MessageStatus::Pending {
2366 metadata.status = MessageStatus::Canceled;
2367 }
2368 });
2369 true
2370 } else {
2371 false
2372 }
2373 }
2374
2375 pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2376 for id in &ids {
2377 if let Some(metadata) = self.messages_metadata.get(id) {
2378 let role = metadata.role.cycle();
2379 self.update_metadata(*id, cx, |metadata| metadata.role = role);
2380 }
2381 }
2382
2383 self.message_roles_updated(ids, cx);
2384 }
2385
2386 fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2387 let mut ranges = Vec::new();
2388 for message in self.messages(cx) {
2389 if ids.contains(&message.id) {
2390 ranges.push(message.anchor_range.clone());
2391 }
2392 }
2393 }
2394
2395 pub fn update_metadata(
2396 &mut self,
2397 id: MessageId,
2398 cx: &mut Context<Self>,
2399 f: impl FnOnce(&mut MessageMetadata),
2400 ) {
2401 let version = self.version.clone();
2402 let timestamp = self.next_timestamp();
2403 if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2404 f(metadata);
2405 metadata.timestamp = timestamp;
2406 let operation = TextThreadOperation::UpdateMessage {
2407 message_id: id,
2408 metadata: metadata.clone(),
2409 version,
2410 };
2411 self.push_op(operation, cx);
2412 cx.emit(TextThreadEvent::MessagesEdited);
2413 cx.notify();
2414 }
2415 }
2416
2417 pub fn insert_message_after(
2418 &mut self,
2419 message_id: MessageId,
2420 role: Role,
2421 status: MessageStatus,
2422 cx: &mut Context<Self>,
2423 ) -> Option<MessageAnchor> {
2424 if let Some(prev_message_ix) = self
2425 .message_anchors
2426 .iter()
2427 .position(|message| message.id == message_id)
2428 {
2429 // Find the next valid message after the one we were given.
2430 let mut next_message_ix = prev_message_ix + 1;
2431 while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2432 if next_message.start.is_valid(self.buffer.read(cx)) {
2433 break;
2434 }
2435 next_message_ix += 1;
2436 }
2437
2438 let buffer = self.buffer.read(cx);
2439 let offset = self
2440 .message_anchors
2441 .get(next_message_ix)
2442 .map_or(buffer.len(), |message| {
2443 buffer.clip_offset(message.start.to_previous_offset(buffer), Bias::Left)
2444 });
2445 Some(self.insert_message_at_offset(offset, role, status, cx))
2446 } else {
2447 None
2448 }
2449 }
2450
2451 fn insert_message_at_offset(
2452 &mut self,
2453 offset: usize,
2454 role: Role,
2455 status: MessageStatus,
2456 cx: &mut Context<Self>,
2457 ) -> MessageAnchor {
2458 let start = self.buffer.update(cx, |buffer, cx| {
2459 buffer.edit([(offset..offset, "\n")], None, cx);
2460 buffer.anchor_before(offset + 1)
2461 });
2462
2463 let version = self.version.clone();
2464 let anchor = MessageAnchor {
2465 id: MessageId(self.next_timestamp()),
2466 start,
2467 };
2468 let metadata = MessageMetadata {
2469 role,
2470 status,
2471 timestamp: anchor.id.0,
2472 cache: None,
2473 };
2474 self.insert_message(anchor.clone(), metadata.clone(), cx);
2475 self.push_op(
2476 TextThreadOperation::InsertMessage {
2477 anchor: anchor.clone(),
2478 metadata,
2479 version,
2480 },
2481 cx,
2482 );
2483 anchor
2484 }
2485
2486 pub fn insert_content(&mut self, content: Content, cx: &mut Context<Self>) {
2487 let buffer = self.buffer.read(cx);
2488 let insertion_ix = match self
2489 .contents
2490 .binary_search_by(|probe| probe.cmp(&content, buffer))
2491 {
2492 Ok(ix) => {
2493 self.contents.remove(ix);
2494 ix
2495 }
2496 Err(ix) => ix,
2497 };
2498 self.contents.insert(insertion_ix, content);
2499 cx.emit(TextThreadEvent::MessagesEdited);
2500 }
2501
2502 pub fn contents<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Content> {
2503 let buffer = self.buffer.read(cx);
2504 self.contents
2505 .iter()
2506 .filter(|content| {
2507 let range = content.range();
2508 range.start.is_valid(buffer) && range.end.is_valid(buffer)
2509 })
2510 .cloned()
2511 }
2512
2513 pub fn split_message(
2514 &mut self,
2515 range: Range<usize>,
2516 cx: &mut Context<Self>,
2517 ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2518 let start_message = self.message_for_offset(range.start, cx);
2519 let end_message = self.message_for_offset(range.end, cx);
2520 if let Some((start_message, end_message)) = start_message.zip(end_message) {
2521 // Prevent splitting when range spans multiple messages.
2522 if start_message.id != end_message.id {
2523 return (None, None);
2524 }
2525
2526 let message = start_message;
2527 let at_end = range.end >= message.offset_range.end.saturating_sub(1);
2528 let role_after = if range.start == range.end || at_end {
2529 Role::User
2530 } else {
2531 message.role
2532 };
2533 let role = message.role;
2534 let mut edited_buffer = false;
2535
2536 let mut suffix_start = None;
2537
2538 // TODO: why did this start panicking?
2539 if range.start > message.offset_range.start
2540 && range.end < message.offset_range.end.saturating_sub(1)
2541 {
2542 if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2543 suffix_start = Some(range.end + 1);
2544 } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2545 suffix_start = Some(range.end);
2546 }
2547 }
2548
2549 let version = self.version.clone();
2550 let suffix = if let Some(suffix_start) = suffix_start {
2551 MessageAnchor {
2552 id: MessageId(self.next_timestamp()),
2553 start: self.buffer.read(cx).anchor_before(suffix_start),
2554 }
2555 } else {
2556 self.buffer.update(cx, |buffer, cx| {
2557 buffer.edit([(range.end..range.end, "\n")], None, cx);
2558 });
2559 edited_buffer = true;
2560 MessageAnchor {
2561 id: MessageId(self.next_timestamp()),
2562 start: self.buffer.read(cx).anchor_before(range.end + 1),
2563 }
2564 };
2565
2566 let suffix_metadata = MessageMetadata {
2567 role: role_after,
2568 status: MessageStatus::Done,
2569 timestamp: suffix.id.0,
2570 cache: None,
2571 };
2572 self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2573 self.push_op(
2574 TextThreadOperation::InsertMessage {
2575 anchor: suffix.clone(),
2576 metadata: suffix_metadata,
2577 version,
2578 },
2579 cx,
2580 );
2581
2582 let new_messages =
2583 if range.start == range.end || range.start == message.offset_range.start {
2584 (None, Some(suffix))
2585 } else {
2586 let mut prefix_end = None;
2587 if range.start > message.offset_range.start
2588 && range.end < message.offset_range.end - 1
2589 {
2590 if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2591 prefix_end = Some(range.start + 1);
2592 } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2593 == Some('\n')
2594 {
2595 prefix_end = Some(range.start);
2596 }
2597 }
2598
2599 let version = self.version.clone();
2600 let selection = if let Some(prefix_end) = prefix_end {
2601 MessageAnchor {
2602 id: MessageId(self.next_timestamp()),
2603 start: self.buffer.read(cx).anchor_before(prefix_end),
2604 }
2605 } else {
2606 self.buffer.update(cx, |buffer, cx| {
2607 buffer.edit([(range.start..range.start, "\n")], None, cx)
2608 });
2609 edited_buffer = true;
2610 MessageAnchor {
2611 id: MessageId(self.next_timestamp()),
2612 start: self.buffer.read(cx).anchor_before(range.end + 1),
2613 }
2614 };
2615
2616 let selection_metadata = MessageMetadata {
2617 role,
2618 status: MessageStatus::Done,
2619 timestamp: selection.id.0,
2620 cache: None,
2621 };
2622 self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2623 self.push_op(
2624 TextThreadOperation::InsertMessage {
2625 anchor: selection.clone(),
2626 metadata: selection_metadata,
2627 version,
2628 },
2629 cx,
2630 );
2631
2632 (Some(selection), Some(suffix))
2633 };
2634
2635 if !edited_buffer {
2636 cx.emit(TextThreadEvent::MessagesEdited);
2637 }
2638 new_messages
2639 } else {
2640 (None, None)
2641 }
2642 }
2643
2644 fn insert_message(
2645 &mut self,
2646 new_anchor: MessageAnchor,
2647 new_metadata: MessageMetadata,
2648 cx: &mut Context<Self>,
2649 ) {
2650 cx.emit(TextThreadEvent::MessagesEdited);
2651
2652 self.messages_metadata.insert(new_anchor.id, new_metadata);
2653
2654 let buffer = self.buffer.read(cx);
2655 let insertion_ix = self
2656 .message_anchors
2657 .iter()
2658 .position(|anchor| {
2659 let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2660 comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2661 })
2662 .unwrap_or(self.message_anchors.len());
2663 self.message_anchors.insert(insertion_ix, new_anchor);
2664 }
2665
2666 pub fn summarize(&mut self, mut replace_old: bool, cx: &mut Context<Self>) {
2667 let Some(model) = LanguageModelRegistry::read_global(cx).thread_summary_model() else {
2668 return;
2669 };
2670
2671 if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_pending()) {
2672 if !model.provider.is_authenticated(cx) {
2673 return;
2674 }
2675
2676 let mut request = self.to_completion_request(Some(&model.model), cx);
2677 request.messages.push(LanguageModelRequestMessage {
2678 role: Role::User,
2679 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2680 cache: false,
2681 });
2682
2683 // If there is no summary, it is set with `done: false` so that "Loading Summary…" can
2684 // be displayed.
2685 match self.summary {
2686 TextThreadSummary::Pending | TextThreadSummary::Error => {
2687 self.summary = TextThreadSummary::Content(TextThreadSummaryContent {
2688 text: "".to_string(),
2689 done: false,
2690 timestamp: clock::Lamport::MIN,
2691 });
2692 replace_old = true;
2693 }
2694 TextThreadSummary::Content(_) => {}
2695 }
2696
2697 self.summary_task = cx.spawn(async move |this, cx| {
2698 let result = async {
2699 let stream = model.model.stream_completion_text(request, cx);
2700 let mut messages = stream.await?;
2701
2702 let mut replaced = !replace_old;
2703 while let Some(message) = messages.stream.next().await {
2704 let text = message?;
2705 let mut lines = text.lines();
2706 this.update(cx, |this, cx| {
2707 let version = this.version.clone();
2708 let timestamp = this.next_timestamp();
2709 let summary = this.summary.content_or_set_empty();
2710 if !replaced && replace_old {
2711 summary.text.clear();
2712 replaced = true;
2713 }
2714 summary.text.extend(lines.next());
2715 summary.timestamp = timestamp;
2716 let operation = TextThreadOperation::UpdateSummary {
2717 summary: summary.clone(),
2718 version,
2719 };
2720 this.push_op(operation, cx);
2721 cx.emit(TextThreadEvent::SummaryChanged);
2722 cx.emit(TextThreadEvent::SummaryGenerated);
2723 })?;
2724
2725 // Stop if the LLM generated multiple lines.
2726 if lines.next().is_some() {
2727 break;
2728 }
2729 }
2730
2731 this.read_with(cx, |this, _cx| {
2732 if let Some(summary) = this.summary.content()
2733 && summary.text.is_empty()
2734 {
2735 bail!("Model generated an empty summary");
2736 }
2737 Ok(())
2738 })??;
2739
2740 this.update(cx, |this, cx| {
2741 let version = this.version.clone();
2742 let timestamp = this.next_timestamp();
2743 if let Some(summary) = this.summary.content_as_mut() {
2744 summary.done = true;
2745 summary.timestamp = timestamp;
2746 let operation = TextThreadOperation::UpdateSummary {
2747 summary: summary.clone(),
2748 version,
2749 };
2750 this.push_op(operation, cx);
2751 cx.emit(TextThreadEvent::SummaryChanged);
2752 cx.emit(TextThreadEvent::SummaryGenerated);
2753 }
2754 })?;
2755
2756 anyhow::Ok(())
2757 }
2758 .await;
2759
2760 if let Err(err) = result {
2761 this.update(cx, |this, cx| {
2762 this.summary = TextThreadSummary::Error;
2763 cx.emit(TextThreadEvent::SummaryChanged);
2764 })
2765 .log_err();
2766 log::error!("Error generating context summary: {}", err);
2767 }
2768
2769 Some(())
2770 });
2771 }
2772 }
2773
2774 fn message_for_offset(&self, offset: usize, cx: &App) -> Option<Message> {
2775 self.messages_for_offsets([offset], cx).pop()
2776 }
2777
2778 pub fn messages_for_offsets(
2779 &self,
2780 offsets: impl IntoIterator<Item = usize>,
2781 cx: &App,
2782 ) -> Vec<Message> {
2783 let mut result = Vec::new();
2784
2785 let mut messages = self.messages(cx).peekable();
2786 let mut offsets = offsets.into_iter().peekable();
2787 let mut current_message = messages.next();
2788 while let Some(offset) = offsets.next() {
2789 // Locate the message that contains the offset.
2790 while current_message.as_ref().is_some_and(|message| {
2791 !message.offset_range.contains(&offset) && messages.peek().is_some()
2792 }) {
2793 current_message = messages.next();
2794 }
2795 let Some(message) = current_message.as_ref() else {
2796 break;
2797 };
2798
2799 // Skip offsets that are in the same message.
2800 while offsets.peek().is_some_and(|offset| {
2801 message.offset_range.contains(offset) || messages.peek().is_none()
2802 }) {
2803 offsets.next();
2804 }
2805
2806 result.push(message.clone());
2807 }
2808 result
2809 }
2810
2811 fn messages_from_anchors<'a>(
2812 &'a self,
2813 message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2814 cx: &'a App,
2815 ) -> impl 'a + Iterator<Item = Message> {
2816 let buffer = self.buffer.read(cx);
2817
2818 Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2819 }
2820
2821 pub fn messages<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Message> {
2822 self.messages_from_anchors(self.message_anchors.iter(), cx)
2823 }
2824
2825 pub fn messages_from_iters<'a>(
2826 buffer: &'a Buffer,
2827 metadata: &'a HashMap<MessageId, MessageMetadata>,
2828 messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2829 ) -> impl 'a + Iterator<Item = Message> {
2830 let mut messages = messages.peekable();
2831
2832 iter::from_fn(move || {
2833 if let Some((start_ix, message_anchor)) = messages.next() {
2834 let metadata = metadata.get(&message_anchor.id)?;
2835
2836 let message_start = message_anchor.start.to_offset(buffer);
2837 let mut message_end = None;
2838 let mut end_ix = start_ix;
2839 while let Some((_, next_message)) = messages.peek() {
2840 if next_message.start.is_valid(buffer) {
2841 message_end = Some(next_message.start);
2842 break;
2843 } else {
2844 end_ix += 1;
2845 messages.next();
2846 }
2847 }
2848 let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2849 let message_end = message_end_anchor.to_offset(buffer);
2850
2851 return Some(Message {
2852 index_range: start_ix..end_ix,
2853 offset_range: message_start..message_end,
2854 anchor_range: message_anchor.start..message_end_anchor,
2855 id: message_anchor.id,
2856 role: metadata.role,
2857 status: metadata.status.clone(),
2858 cache: metadata.cache.clone(),
2859 });
2860 }
2861 None
2862 })
2863 }
2864
2865 pub fn save(
2866 &mut self,
2867 debounce: Option<Duration>,
2868 fs: Arc<dyn Fs>,
2869 cx: &mut Context<TextThread>,
2870 ) {
2871 if self.replica_id() != ReplicaId::default() {
2872 // Prevent saving a remote context for now.
2873 return;
2874 }
2875
2876 self.pending_save = cx.spawn(async move |this, cx| {
2877 if let Some(debounce) = debounce {
2878 cx.background_executor().timer(debounce).await;
2879 }
2880
2881 let (old_path, summary) = this.read_with(cx, |this, _| {
2882 let path = this.path.clone();
2883 let summary = if let Some(summary) = this.summary.content() {
2884 if summary.done {
2885 Some(summary.text.clone())
2886 } else {
2887 None
2888 }
2889 } else {
2890 None
2891 };
2892 (path, summary)
2893 })?;
2894
2895 if let Some(summary) = summary {
2896 let context = this.read_with(cx, |this, cx| this.serialize(cx))?;
2897 let mut discriminant = 1;
2898 let mut new_path;
2899 loop {
2900 new_path = text_threads_dir().join(&format!(
2901 "{} - {}.zed.json",
2902 summary.trim(),
2903 discriminant
2904 ));
2905 if fs.is_file(&new_path).await {
2906 discriminant += 1;
2907 } else {
2908 break;
2909 }
2910 }
2911
2912 fs.create_dir(text_threads_dir().as_ref()).await?;
2913
2914 // rename before write ensures that only one file exists
2915 if let Some(old_path) = old_path.as_ref()
2916 && new_path.as_path() != old_path.as_ref()
2917 {
2918 fs.rename(
2919 old_path,
2920 &new_path,
2921 RenameOptions {
2922 overwrite: true,
2923 ignore_if_exists: true,
2924 },
2925 )
2926 .await?;
2927 }
2928
2929 // update path before write in case it fails
2930 this.update(cx, {
2931 let new_path: Arc<Path> = new_path.clone().into();
2932 move |this, cx| {
2933 this.path = Some(new_path.clone());
2934 cx.emit(TextThreadEvent::PathChanged { old_path, new_path });
2935 }
2936 })
2937 .ok();
2938
2939 fs.atomic_write(new_path, serde_json::to_string(&context).unwrap())
2940 .await?;
2941 }
2942
2943 Ok(())
2944 });
2945 }
2946
2947 pub fn set_custom_summary(&mut self, custom_summary: String, cx: &mut Context<Self>) {
2948 let timestamp = self.next_timestamp();
2949 let summary = self.summary.content_or_set_empty();
2950 summary.timestamp = timestamp;
2951 summary.done = true;
2952 summary.text = custom_summary;
2953 cx.emit(TextThreadEvent::SummaryChanged);
2954 }
2955
2956 fn update_model_request_usage(&self, amount: u32, limit: UsageLimit, cx: &mut App) {
2957 let Some(project) = &self.project else {
2958 return;
2959 };
2960 project.read(cx).user_store().update(cx, |user_store, cx| {
2961 user_store.update_model_request_usage(
2962 ModelRequestUsage(RequestUsage {
2963 amount: amount as i32,
2964 limit,
2965 }),
2966 cx,
2967 )
2968 });
2969 }
2970}
2971
2972#[derive(Debug, Default)]
2973pub struct TextThreadVersion {
2974 text_thread: clock::Global,
2975 buffer: clock::Global,
2976}
2977
2978impl TextThreadVersion {
2979 pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2980 Self {
2981 text_thread: language::proto::deserialize_version(&proto.context_version),
2982 buffer: language::proto::deserialize_version(&proto.buffer_version),
2983 }
2984 }
2985
2986 pub fn to_proto(&self, context_id: TextThreadId) -> proto::ContextVersion {
2987 proto::ContextVersion {
2988 context_id: context_id.to_proto(),
2989 context_version: language::proto::serialize_version(&self.text_thread),
2990 buffer_version: language::proto::serialize_version(&self.buffer),
2991 }
2992 }
2993}
2994
2995#[derive(Debug, Clone)]
2996pub struct ParsedSlashCommand {
2997 pub name: String,
2998 pub arguments: SmallVec<[String; 3]>,
2999 pub status: PendingSlashCommandStatus,
3000 pub source_range: Range<language::Anchor>,
3001}
3002
3003#[derive(Debug)]
3004pub struct InvokedSlashCommand {
3005 pub name: SharedString,
3006 pub range: Range<language::Anchor>,
3007 pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
3008 pub status: InvokedSlashCommandStatus,
3009 pub transaction: Option<language::TransactionId>,
3010 timestamp: clock::Lamport,
3011}
3012
3013#[derive(Debug)]
3014pub enum InvokedSlashCommandStatus {
3015 Running(Task<()>),
3016 Error(SharedString),
3017 Finished,
3018}
3019
3020#[derive(Debug, Clone)]
3021pub enum PendingSlashCommandStatus {
3022 Idle,
3023 Running { _task: Shared<Task<()>> },
3024 Error(String),
3025}
3026
3027#[derive(Debug, Clone)]
3028pub struct PendingToolUse {
3029 pub id: LanguageModelToolUseId,
3030 pub name: String,
3031 pub input: serde_json::Value,
3032 pub status: PendingToolUseStatus,
3033 pub source_range: Range<language::Anchor>,
3034}
3035
3036#[derive(Debug, Clone)]
3037pub enum PendingToolUseStatus {
3038 Idle,
3039 Running { _task: Shared<Task<()>> },
3040 Error(String),
3041}
3042
3043impl PendingToolUseStatus {
3044 pub fn is_idle(&self) -> bool {
3045 matches!(self, PendingToolUseStatus::Idle)
3046 }
3047}
3048
3049#[derive(Serialize, Deserialize)]
3050pub struct SavedMessage {
3051 pub id: MessageId,
3052 pub start: usize,
3053 pub metadata: MessageMetadata,
3054}
3055
3056#[derive(Serialize, Deserialize)]
3057pub struct SavedTextThread {
3058 pub id: Option<TextThreadId>,
3059 pub zed: String,
3060 pub version: String,
3061 pub text: String,
3062 pub messages: Vec<SavedMessage>,
3063 pub summary: String,
3064 pub slash_command_output_sections:
3065 Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3066 #[serde(default)]
3067 pub thought_process_output_sections: Vec<ThoughtProcessOutputSection<usize>>,
3068}
3069
3070impl SavedTextThread {
3071 pub const VERSION: &'static str = "0.4.0";
3072
3073 pub fn from_json(json: &str) -> Result<Self> {
3074 let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3075 match saved_context_json
3076 .get("version")
3077 .context("version not found")?
3078 {
3079 serde_json::Value::String(version) => match version.as_str() {
3080 SavedTextThread::VERSION => Ok(serde_json::from_value::<SavedTextThread>(
3081 saved_context_json,
3082 )?),
3083 SavedContextV0_3_0::VERSION => {
3084 let saved_context =
3085 serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3086 Ok(saved_context.upgrade())
3087 }
3088 SavedContextV0_2_0::VERSION => {
3089 let saved_context =
3090 serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3091 Ok(saved_context.upgrade())
3092 }
3093 SavedContextV0_1_0::VERSION => {
3094 let saved_context =
3095 serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3096 Ok(saved_context.upgrade())
3097 }
3098 _ => anyhow::bail!("unrecognized saved context version: {version:?}"),
3099 },
3100 _ => anyhow::bail!("version not found on saved context"),
3101 }
3102 }
3103
3104 fn into_ops(
3105 self,
3106 buffer: &Entity<Buffer>,
3107 cx: &mut Context<TextThread>,
3108 ) -> Vec<TextThreadOperation> {
3109 let mut operations = Vec::new();
3110 let mut version = clock::Global::new();
3111 let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3112
3113 let mut first_message_metadata = None;
3114 for message in self.messages {
3115 if message.id == MessageId(clock::Lamport::MIN) {
3116 first_message_metadata = Some(message.metadata);
3117 } else {
3118 operations.push(TextThreadOperation::InsertMessage {
3119 anchor: MessageAnchor {
3120 id: message.id,
3121 start: buffer.read(cx).anchor_before(message.start),
3122 },
3123 metadata: MessageMetadata {
3124 role: message.metadata.role,
3125 status: message.metadata.status,
3126 timestamp: message.metadata.timestamp,
3127 cache: None,
3128 },
3129 version: version.clone(),
3130 });
3131 version.observe(message.id.0);
3132 next_timestamp.observe(message.id.0);
3133 }
3134 }
3135
3136 if let Some(metadata) = first_message_metadata {
3137 let timestamp = next_timestamp.tick();
3138 operations.push(TextThreadOperation::UpdateMessage {
3139 message_id: MessageId(clock::Lamport::MIN),
3140 metadata: MessageMetadata {
3141 role: metadata.role,
3142 status: metadata.status,
3143 timestamp,
3144 cache: None,
3145 },
3146 version: version.clone(),
3147 });
3148 version.observe(timestamp);
3149 }
3150
3151 let buffer = buffer.read(cx);
3152 for section in self.slash_command_output_sections {
3153 let timestamp = next_timestamp.tick();
3154 operations.push(TextThreadOperation::SlashCommandOutputSectionAdded {
3155 timestamp,
3156 section: SlashCommandOutputSection {
3157 range: buffer.anchor_after(section.range.start)
3158 ..buffer.anchor_before(section.range.end),
3159 icon: section.icon,
3160 label: section.label,
3161 metadata: section.metadata,
3162 },
3163 version: version.clone(),
3164 });
3165
3166 version.observe(timestamp);
3167 }
3168
3169 for section in self.thought_process_output_sections {
3170 let timestamp = next_timestamp.tick();
3171 operations.push(TextThreadOperation::ThoughtProcessOutputSectionAdded {
3172 timestamp,
3173 section: ThoughtProcessOutputSection {
3174 range: buffer.anchor_after(section.range.start)
3175 ..buffer.anchor_before(section.range.end),
3176 },
3177 version: version.clone(),
3178 });
3179
3180 version.observe(timestamp);
3181 }
3182
3183 let timestamp = next_timestamp.tick();
3184 operations.push(TextThreadOperation::UpdateSummary {
3185 summary: TextThreadSummaryContent {
3186 text: self.summary,
3187 done: true,
3188 timestamp,
3189 },
3190 version: version.clone(),
3191 });
3192 version.observe(timestamp);
3193
3194 operations
3195 }
3196}
3197
3198#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3199struct SavedMessageIdPreV0_4_0(usize);
3200
3201#[derive(Serialize, Deserialize)]
3202struct SavedMessagePreV0_4_0 {
3203 id: SavedMessageIdPreV0_4_0,
3204 start: usize,
3205}
3206
3207#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3208struct SavedMessageMetadataPreV0_4_0 {
3209 role: Role,
3210 status: MessageStatus,
3211}
3212
3213#[derive(Serialize, Deserialize)]
3214struct SavedContextV0_3_0 {
3215 id: Option<TextThreadId>,
3216 zed: String,
3217 version: String,
3218 text: String,
3219 messages: Vec<SavedMessagePreV0_4_0>,
3220 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3221 summary: String,
3222 slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3223}
3224
3225impl SavedContextV0_3_0 {
3226 const VERSION: &'static str = "0.3.0";
3227
3228 fn upgrade(self) -> SavedTextThread {
3229 SavedTextThread {
3230 id: self.id,
3231 zed: self.zed,
3232 version: SavedTextThread::VERSION.into(),
3233 text: self.text,
3234 messages: self
3235 .messages
3236 .into_iter()
3237 .filter_map(|message| {
3238 let metadata = self.message_metadata.get(&message.id)?;
3239 let timestamp = clock::Lamport {
3240 replica_id: ReplicaId::default(),
3241 value: message.id.0 as u32,
3242 };
3243 Some(SavedMessage {
3244 id: MessageId(timestamp),
3245 start: message.start,
3246 metadata: MessageMetadata {
3247 role: metadata.role,
3248 status: metadata.status.clone(),
3249 timestamp,
3250 cache: None,
3251 },
3252 })
3253 })
3254 .collect(),
3255 summary: self.summary,
3256 slash_command_output_sections: self.slash_command_output_sections,
3257 thought_process_output_sections: Vec::new(),
3258 }
3259 }
3260}
3261
3262#[derive(Serialize, Deserialize)]
3263struct SavedContextV0_2_0 {
3264 id: Option<TextThreadId>,
3265 zed: String,
3266 version: String,
3267 text: String,
3268 messages: Vec<SavedMessagePreV0_4_0>,
3269 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3270 summary: String,
3271}
3272
3273impl SavedContextV0_2_0 {
3274 const VERSION: &'static str = "0.2.0";
3275
3276 fn upgrade(self) -> SavedTextThread {
3277 SavedContextV0_3_0 {
3278 id: self.id,
3279 zed: self.zed,
3280 version: SavedContextV0_3_0::VERSION.to_string(),
3281 text: self.text,
3282 messages: self.messages,
3283 message_metadata: self.message_metadata,
3284 summary: self.summary,
3285 slash_command_output_sections: Vec::new(),
3286 }
3287 .upgrade()
3288 }
3289}
3290
3291#[derive(Serialize, Deserialize)]
3292struct SavedContextV0_1_0 {
3293 id: Option<TextThreadId>,
3294 zed: String,
3295 version: String,
3296 text: String,
3297 messages: Vec<SavedMessagePreV0_4_0>,
3298 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3299 summary: String,
3300 api_url: Option<String>,
3301 model: OpenAiModel,
3302}
3303
3304impl SavedContextV0_1_0 {
3305 const VERSION: &'static str = "0.1.0";
3306
3307 fn upgrade(self) -> SavedTextThread {
3308 SavedContextV0_2_0 {
3309 id: self.id,
3310 zed: self.zed,
3311 version: SavedContextV0_2_0::VERSION.to_string(),
3312 text: self.text,
3313 messages: self.messages,
3314 message_metadata: self.message_metadata,
3315 summary: self.summary,
3316 }
3317 .upgrade()
3318 }
3319}
3320
3321#[derive(Debug, Clone)]
3322pub struct SavedTextThreadMetadata {
3323 pub title: SharedString,
3324 pub path: Arc<Path>,
3325 pub mtime: chrono::DateTime<chrono::Local>,
3326}