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, UsageLimit};
11use collections::{HashMap, HashSet};
12use fs::{Fs, RenameOptions};
13
14use futures::{FutureExt, StreamExt, future::Shared};
15use gpui::{
16 App, AppContext as _, Context, Entity, EventEmitter, RenderImage, SharedString, Subscription,
17 Task,
18};
19use language::{AnchorRangeExt, Bias, Buffer, LanguageRegistry, OffsetRangeExt, Point, ToOffset};
20use language_model::{
21 LanguageModel, LanguageModelCacheConfiguration, LanguageModelCompletionEvent,
22 LanguageModelImage, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
23 LanguageModelToolUseId, MessageContent, PaymentRequiredError, Role, StopReason,
24 report_assistant_event,
25};
26use open_ai::Model as OpenAiModel;
27use paths::text_threads_dir;
28use project::Project;
29use prompt_store::PromptBuilder;
30use serde::{Deserialize, Serialize};
31use settings::Settings;
32use smallvec::SmallVec;
33use std::{
34 cmp::{Ordering, max},
35 fmt::{Debug, Write as _},
36 iter, mem,
37 ops::Range,
38 path::Path,
39 sync::Arc,
40 time::{Duration, Instant},
41};
42use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
43use text::{BufferSnapshot, ToPoint};
44use ui::IconName;
45use util::{ResultExt, TryFutureExt, post_inc};
46use uuid::Uuid;
47
48#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
49pub struct TextThreadId(String);
50
51impl TextThreadId {
52 pub fn new() -> Self {
53 Self(Uuid::new_v4().to_string())
54 }
55
56 pub fn from_proto(id: String) -> Self {
57 Self(id)
58 }
59
60 pub fn to_proto(&self) -> String {
61 self.0.clone()
62 }
63}
64
65#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
66pub struct MessageId(pub clock::Lamport);
67
68impl MessageId {
69 pub fn as_u64(self) -> u64 {
70 self.0.as_u64()
71 }
72}
73
74#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
75pub enum MessageStatus {
76 Pending,
77 Done,
78 Error(SharedString),
79 Canceled,
80}
81
82impl MessageStatus {
83 pub fn from_proto(status: proto::ContextMessageStatus) -> MessageStatus {
84 match status.variant {
85 Some(proto::context_message_status::Variant::Pending(_)) => MessageStatus::Pending,
86 Some(proto::context_message_status::Variant::Done(_)) => MessageStatus::Done,
87 Some(proto::context_message_status::Variant::Error(error)) => {
88 MessageStatus::Error(error.message.into())
89 }
90 Some(proto::context_message_status::Variant::Canceled(_)) => MessageStatus::Canceled,
91 None => MessageStatus::Pending,
92 }
93 }
94
95 pub fn to_proto(&self) -> proto::ContextMessageStatus {
96 match self {
97 MessageStatus::Pending => proto::ContextMessageStatus {
98 variant: Some(proto::context_message_status::Variant::Pending(
99 proto::context_message_status::Pending {},
100 )),
101 },
102 MessageStatus::Done => proto::ContextMessageStatus {
103 variant: Some(proto::context_message_status::Variant::Done(
104 proto::context_message_status::Done {},
105 )),
106 },
107 MessageStatus::Error(message) => proto::ContextMessageStatus {
108 variant: Some(proto::context_message_status::Variant::Error(
109 proto::context_message_status::Error {
110 message: message.to_string(),
111 },
112 )),
113 },
114 MessageStatus::Canceled => proto::ContextMessageStatus {
115 variant: Some(proto::context_message_status::Variant::Canceled(
116 proto::context_message_status::Canceled {},
117 )),
118 },
119 }
120 }
121}
122
123#[derive(Clone, Debug)]
124pub enum TextThreadOperation {
125 InsertMessage {
126 anchor: MessageAnchor,
127 metadata: MessageMetadata,
128 version: clock::Global,
129 },
130 UpdateMessage {
131 message_id: MessageId,
132 metadata: MessageMetadata,
133 version: clock::Global,
134 },
135 UpdateSummary {
136 summary: TextThreadSummaryContent,
137 version: clock::Global,
138 },
139 SlashCommandStarted {
140 id: InvokedSlashCommandId,
141 output_range: Range<language::Anchor>,
142 name: String,
143 version: clock::Global,
144 },
145 SlashCommandFinished {
146 id: InvokedSlashCommandId,
147 timestamp: clock::Lamport,
148 error_message: Option<String>,
149 version: clock::Global,
150 },
151 SlashCommandOutputSectionAdded {
152 timestamp: clock::Lamport,
153 section: SlashCommandOutputSection<language::Anchor>,
154 version: clock::Global,
155 },
156 ThoughtProcessOutputSectionAdded {
157 timestamp: clock::Lamport,
158 section: ThoughtProcessOutputSection<language::Anchor>,
159 version: clock::Global,
160 },
161 BufferOperation(language::Operation),
162}
163
164impl TextThreadOperation {
165 pub fn from_proto(op: proto::ContextOperation) -> Result<Self> {
166 match op.variant.context("invalid variant")? {
167 proto::context_operation::Variant::InsertMessage(insert) => {
168 let message = insert.message.context("invalid message")?;
169 let id = MessageId(language::proto::deserialize_timestamp(
170 message.id.context("invalid id")?,
171 ));
172 Ok(Self::InsertMessage {
173 anchor: MessageAnchor {
174 id,
175 start: language::proto::deserialize_anchor(
176 message.start.context("invalid anchor")?,
177 )
178 .context("invalid anchor")?,
179 },
180 metadata: MessageMetadata {
181 role: Role::from_proto(message.role),
182 status: MessageStatus::from_proto(
183 message.status.context("invalid status")?,
184 ),
185 timestamp: id.0,
186 cache: None,
187 },
188 version: language::proto::deserialize_version(&insert.version),
189 })
190 }
191 proto::context_operation::Variant::UpdateMessage(update) => Ok(Self::UpdateMessage {
192 message_id: MessageId(language::proto::deserialize_timestamp(
193 update.message_id.context("invalid message id")?,
194 )),
195 metadata: MessageMetadata {
196 role: Role::from_proto(update.role),
197 status: MessageStatus::from_proto(update.status.context("invalid status")?),
198 timestamp: language::proto::deserialize_timestamp(
199 update.timestamp.context("invalid timestamp")?,
200 ),
201 cache: None,
202 },
203 version: language::proto::deserialize_version(&update.version),
204 }),
205 proto::context_operation::Variant::UpdateSummary(update) => Ok(Self::UpdateSummary {
206 summary: TextThreadSummaryContent {
207 text: update.summary,
208 done: update.done,
209 timestamp: language::proto::deserialize_timestamp(
210 update.timestamp.context("invalid timestamp")?,
211 ),
212 },
213 version: language::proto::deserialize_version(&update.version),
214 }),
215 proto::context_operation::Variant::SlashCommandStarted(message) => {
216 Ok(Self::SlashCommandStarted {
217 id: InvokedSlashCommandId(language::proto::deserialize_timestamp(
218 message.id.context("invalid id")?,
219 )),
220 output_range: language::proto::deserialize_anchor_range(
221 message.output_range.context("invalid range")?,
222 )?,
223 name: message.name,
224 version: language::proto::deserialize_version(&message.version),
225 })
226 }
227 proto::context_operation::Variant::SlashCommandOutputSectionAdded(message) => {
228 let section = message.section.context("missing section")?;
229 Ok(Self::SlashCommandOutputSectionAdded {
230 timestamp: language::proto::deserialize_timestamp(
231 message.timestamp.context("missing timestamp")?,
232 ),
233 section: SlashCommandOutputSection {
234 range: language::proto::deserialize_anchor_range(
235 section.range.context("invalid range")?,
236 )?,
237 icon: section.icon_name.parse()?,
238 label: section.label.into(),
239 metadata: section
240 .metadata
241 .and_then(|metadata| serde_json::from_str(&metadata).log_err()),
242 },
243 version: language::proto::deserialize_version(&message.version),
244 })
245 }
246 proto::context_operation::Variant::SlashCommandCompleted(message) => {
247 Ok(Self::SlashCommandFinished {
248 id: InvokedSlashCommandId(language::proto::deserialize_timestamp(
249 message.id.context("invalid id")?,
250 )),
251 timestamp: language::proto::deserialize_timestamp(
252 message.timestamp.context("missing timestamp")?,
253 ),
254 error_message: message.error_message,
255 version: language::proto::deserialize_version(&message.version),
256 })
257 }
258 proto::context_operation::Variant::ThoughtProcessOutputSectionAdded(message) => {
259 let section = message.section.context("missing section")?;
260 Ok(Self::ThoughtProcessOutputSectionAdded {
261 timestamp: language::proto::deserialize_timestamp(
262 message.timestamp.context("missing timestamp")?,
263 ),
264 section: ThoughtProcessOutputSection {
265 range: language::proto::deserialize_anchor_range(
266 section.range.context("invalid range")?,
267 )?,
268 },
269 version: language::proto::deserialize_version(&message.version),
270 })
271 }
272 proto::context_operation::Variant::BufferOperation(op) => Ok(Self::BufferOperation(
273 language::proto::deserialize_operation(
274 op.operation.context("invalid buffer operation")?,
275 )?,
276 )),
277 }
278 }
279
280 pub fn to_proto(&self) -> proto::ContextOperation {
281 match self {
282 Self::InsertMessage {
283 anchor,
284 metadata,
285 version,
286 } => proto::ContextOperation {
287 variant: Some(proto::context_operation::Variant::InsertMessage(
288 proto::context_operation::InsertMessage {
289 message: Some(proto::ContextMessage {
290 id: Some(language::proto::serialize_timestamp(anchor.id.0)),
291 start: Some(language::proto::serialize_anchor(&anchor.start)),
292 role: metadata.role.to_proto() as i32,
293 status: Some(metadata.status.to_proto()),
294 }),
295 version: language::proto::serialize_version(version),
296 },
297 )),
298 },
299 Self::UpdateMessage {
300 message_id,
301 metadata,
302 version,
303 } => proto::ContextOperation {
304 variant: Some(proto::context_operation::Variant::UpdateMessage(
305 proto::context_operation::UpdateMessage {
306 message_id: Some(language::proto::serialize_timestamp(message_id.0)),
307 role: metadata.role.to_proto() as i32,
308 status: Some(metadata.status.to_proto()),
309 timestamp: Some(language::proto::serialize_timestamp(metadata.timestamp)),
310 version: language::proto::serialize_version(version),
311 },
312 )),
313 },
314 Self::UpdateSummary { summary, version } => proto::ContextOperation {
315 variant: Some(proto::context_operation::Variant::UpdateSummary(
316 proto::context_operation::UpdateSummary {
317 summary: summary.text.clone(),
318 done: summary.done,
319 timestamp: Some(language::proto::serialize_timestamp(summary.timestamp)),
320 version: language::proto::serialize_version(version),
321 },
322 )),
323 },
324 Self::SlashCommandStarted {
325 id,
326 output_range,
327 name,
328 version,
329 } => proto::ContextOperation {
330 variant: Some(proto::context_operation::Variant::SlashCommandStarted(
331 proto::context_operation::SlashCommandStarted {
332 id: Some(language::proto::serialize_timestamp(id.0)),
333 output_range: Some(language::proto::serialize_anchor_range(
334 output_range.clone(),
335 )),
336 name: name.clone(),
337 version: language::proto::serialize_version(version),
338 },
339 )),
340 },
341 Self::SlashCommandOutputSectionAdded {
342 timestamp,
343 section,
344 version,
345 } => proto::ContextOperation {
346 variant: Some(
347 proto::context_operation::Variant::SlashCommandOutputSectionAdded(
348 proto::context_operation::SlashCommandOutputSectionAdded {
349 timestamp: Some(language::proto::serialize_timestamp(*timestamp)),
350 section: Some({
351 let icon_name: &'static str = section.icon.into();
352 proto::SlashCommandOutputSection {
353 range: Some(language::proto::serialize_anchor_range(
354 section.range.clone(),
355 )),
356 icon_name: icon_name.to_string(),
357 label: section.label.to_string(),
358 metadata: section.metadata.as_ref().and_then(|metadata| {
359 serde_json::to_string(metadata).log_err()
360 }),
361 }
362 }),
363 version: language::proto::serialize_version(version),
364 },
365 ),
366 ),
367 },
368 Self::SlashCommandFinished {
369 id,
370 timestamp,
371 error_message,
372 version,
373 } => proto::ContextOperation {
374 variant: Some(proto::context_operation::Variant::SlashCommandCompleted(
375 proto::context_operation::SlashCommandCompleted {
376 id: Some(language::proto::serialize_timestamp(id.0)),
377 timestamp: Some(language::proto::serialize_timestamp(*timestamp)),
378 error_message: error_message.clone(),
379 version: language::proto::serialize_version(version),
380 },
381 )),
382 },
383 Self::ThoughtProcessOutputSectionAdded {
384 timestamp,
385 section,
386 version,
387 } => proto::ContextOperation {
388 variant: Some(
389 proto::context_operation::Variant::ThoughtProcessOutputSectionAdded(
390 proto::context_operation::ThoughtProcessOutputSectionAdded {
391 timestamp: Some(language::proto::serialize_timestamp(*timestamp)),
392 section: Some({
393 proto::ThoughtProcessOutputSection {
394 range: Some(language::proto::serialize_anchor_range(
395 section.range.clone(),
396 )),
397 }
398 }),
399 version: language::proto::serialize_version(version),
400 },
401 ),
402 ),
403 },
404 Self::BufferOperation(operation) => proto::ContextOperation {
405 variant: Some(proto::context_operation::Variant::BufferOperation(
406 proto::context_operation::BufferOperation {
407 operation: Some(language::proto::serialize_operation(operation)),
408 },
409 )),
410 },
411 }
412 }
413
414 fn timestamp(&self) -> clock::Lamport {
415 match self {
416 Self::InsertMessage { anchor, .. } => anchor.id.0,
417 Self::UpdateMessage { metadata, .. } => metadata.timestamp,
418 Self::UpdateSummary { summary, .. } => summary.timestamp,
419 Self::SlashCommandStarted { id, .. } => id.0,
420 Self::SlashCommandOutputSectionAdded { timestamp, .. }
421 | Self::SlashCommandFinished { timestamp, .. }
422 | Self::ThoughtProcessOutputSectionAdded { timestamp, .. } => *timestamp,
423 Self::BufferOperation(_) => {
424 panic!("reading the timestamp of a buffer operation is not supported")
425 }
426 }
427 }
428
429 /// Returns the current version of the context operation.
430 pub fn version(&self) -> &clock::Global {
431 match self {
432 Self::InsertMessage { version, .. }
433 | Self::UpdateMessage { version, .. }
434 | Self::UpdateSummary { version, .. }
435 | Self::SlashCommandStarted { version, .. }
436 | Self::SlashCommandOutputSectionAdded { version, .. }
437 | Self::SlashCommandFinished { version, .. }
438 | Self::ThoughtProcessOutputSectionAdded { version, .. } => version,
439 Self::BufferOperation(_) => {
440 panic!("reading the version of a buffer operation is not supported")
441 }
442 }
443 }
444}
445
446#[derive(Debug, Clone)]
447pub enum TextThreadEvent {
448 ShowAssistError(SharedString),
449 ShowPaymentRequiredError,
450 MessagesEdited,
451 SummaryChanged,
452 SummaryGenerated,
453 PathChanged {
454 old_path: Option<Arc<Path>>,
455 new_path: Arc<Path>,
456 },
457 StreamedCompletion,
458 StartedThoughtProcess(Range<language::Anchor>),
459 EndedThoughtProcess(language::Anchor),
460 InvokedSlashCommandChanged {
461 command_id: InvokedSlashCommandId,
462 },
463 ParsedSlashCommandsUpdated {
464 removed: Vec<Range<language::Anchor>>,
465 updated: Vec<ParsedSlashCommand>,
466 },
467 SlashCommandOutputSectionAdded {
468 section: SlashCommandOutputSection<language::Anchor>,
469 },
470 Operation(TextThreadOperation),
471}
472
473#[derive(Clone, Debug, Eq, PartialEq)]
474pub enum TextThreadSummary {
475 Pending,
476 Content(TextThreadSummaryContent),
477 Error,
478}
479
480#[derive(Clone, Debug, Eq, PartialEq)]
481pub struct TextThreadSummaryContent {
482 pub text: String,
483 pub done: bool,
484 pub timestamp: clock::Lamport,
485}
486
487impl TextThreadSummary {
488 pub const DEFAULT: &str = "New Text Thread";
489
490 pub fn or_default(&self) -> SharedString {
491 self.unwrap_or(Self::DEFAULT)
492 }
493
494 pub fn unwrap_or(&self, message: impl Into<SharedString>) -> SharedString {
495 self.content()
496 .map_or_else(|| message.into(), |content| content.text.clone().into())
497 }
498
499 pub fn content(&self) -> Option<&TextThreadSummaryContent> {
500 match self {
501 TextThreadSummary::Content(content) => Some(content),
502 TextThreadSummary::Pending | TextThreadSummary::Error => None,
503 }
504 }
505
506 fn content_as_mut(&mut self) -> Option<&mut TextThreadSummaryContent> {
507 match self {
508 TextThreadSummary::Content(content) => Some(content),
509 TextThreadSummary::Pending | TextThreadSummary::Error => None,
510 }
511 }
512
513 fn content_or_set_empty(&mut self) -> &mut TextThreadSummaryContent {
514 match self {
515 TextThreadSummary::Content(content) => content,
516 TextThreadSummary::Pending | TextThreadSummary::Error => {
517 let content = TextThreadSummaryContent {
518 text: "".to_string(),
519 done: false,
520 timestamp: clock::Lamport::MIN,
521 };
522 *self = TextThreadSummary::Content(content);
523 self.content_as_mut().unwrap()
524 }
525 }
526 }
527
528 pub fn is_pending(&self) -> bool {
529 matches!(self, TextThreadSummary::Pending)
530 }
531
532 fn timestamp(&self) -> Option<clock::Lamport> {
533 match self {
534 TextThreadSummary::Content(content) => Some(content.timestamp),
535 TextThreadSummary::Pending | TextThreadSummary::Error => None,
536 }
537 }
538}
539
540impl PartialOrd for TextThreadSummary {
541 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
542 self.timestamp().partial_cmp(&other.timestamp())
543 }
544}
545
546#[derive(Clone, Debug, Eq, PartialEq)]
547pub struct MessageAnchor {
548 pub id: MessageId,
549 pub start: language::Anchor,
550}
551
552#[derive(Clone, Debug, Eq, PartialEq)]
553pub enum CacheStatus {
554 Pending,
555 Cached,
556}
557
558#[derive(Clone, Debug, Eq, PartialEq)]
559pub struct MessageCacheMetadata {
560 pub is_anchor: bool,
561 pub is_final_anchor: bool,
562 pub status: CacheStatus,
563 pub cached_at: clock::Global,
564}
565
566#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
567pub struct MessageMetadata {
568 pub role: Role,
569 pub status: MessageStatus,
570 pub timestamp: clock::Lamport,
571 #[serde(skip)]
572 pub cache: Option<MessageCacheMetadata>,
573}
574
575impl From<&Message> for MessageMetadata {
576 fn from(message: &Message) -> Self {
577 Self {
578 role: message.role,
579 status: message.status.clone(),
580 timestamp: message.id.0,
581 cache: message.cache.clone(),
582 }
583 }
584}
585
586impl MessageMetadata {
587 pub fn is_cache_valid(&self, buffer: &BufferSnapshot, range: &Range<usize>) -> bool {
588 match &self.cache {
589 Some(MessageCacheMetadata { cached_at, .. }) => !buffer.has_edits_since_in_range(
590 cached_at,
591 Range {
592 start: buffer.anchor_at(range.start, Bias::Right),
593 end: buffer.anchor_at(range.end, Bias::Left),
594 },
595 ),
596 _ => false,
597 }
598 }
599}
600
601#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
602pub struct ThoughtProcessOutputSection<T> {
603 pub range: Range<T>,
604}
605
606impl ThoughtProcessOutputSection<language::Anchor> {
607 pub fn is_valid(&self, buffer: &language::TextBuffer) -> bool {
608 self.range.start.is_valid(buffer) && !self.range.to_offset(buffer).is_empty()
609 }
610}
611
612#[derive(Clone, Debug)]
613pub struct Message {
614 pub offset_range: Range<usize>,
615 pub index_range: Range<usize>,
616 pub anchor_range: Range<language::Anchor>,
617 pub id: MessageId,
618 pub role: Role,
619 pub status: MessageStatus,
620 pub cache: Option<MessageCacheMetadata>,
621}
622
623#[derive(Debug, Clone)]
624pub enum Content {
625 Image {
626 anchor: language::Anchor,
627 image_id: u64,
628 render_image: Arc<RenderImage>,
629 image: Shared<Task<Option<LanguageModelImage>>>,
630 },
631}
632
633impl Content {
634 fn range(&self) -> Range<language::Anchor> {
635 match self {
636 Self::Image { anchor, .. } => *anchor..*anchor,
637 }
638 }
639
640 fn cmp(&self, other: &Self, buffer: &BufferSnapshot) -> Ordering {
641 let self_range = self.range();
642 let other_range = other.range();
643 if self_range.end.cmp(&other_range.start, buffer).is_lt() {
644 Ordering::Less
645 } else if self_range.start.cmp(&other_range.end, buffer).is_gt() {
646 Ordering::Greater
647 } else {
648 Ordering::Equal
649 }
650 }
651}
652
653struct PendingCompletion {
654 id: usize,
655 assistant_message_id: MessageId,
656 _task: Task<()>,
657}
658
659#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
660pub struct InvokedSlashCommandId(clock::Lamport);
661
662pub struct TextThread {
663 id: TextThreadId,
664 timestamp: clock::Lamport,
665 version: clock::Global,
666 pub(crate) pending_ops: Vec<TextThreadOperation>,
667 operations: Vec<TextThreadOperation>,
668 buffer: Entity<Buffer>,
669 pub(crate) parsed_slash_commands: Vec<ParsedSlashCommand>,
670 invoked_slash_commands: HashMap<InvokedSlashCommandId, InvokedSlashCommand>,
671 edits_since_last_parse: language::Subscription<usize>,
672 slash_commands: Arc<SlashCommandWorkingSet>,
673 pub(crate) slash_command_output_sections: Vec<SlashCommandOutputSection<language::Anchor>>,
674 thought_process_output_sections: Vec<ThoughtProcessOutputSection<language::Anchor>>,
675 pub(crate) message_anchors: Vec<MessageAnchor>,
676 contents: Vec<Content>,
677 pub(crate) messages_metadata: HashMap<MessageId, MessageMetadata>,
678 summary: TextThreadSummary,
679 summary_task: Task<Option<()>>,
680 completion_count: usize,
681 pending_completions: Vec<PendingCompletion>,
682 pub(crate) token_count: Option<u64>,
683 pending_token_count: Task<Option<()>>,
684 pending_save: Task<Result<()>>,
685 pending_cache_warming_task: Task<Option<()>>,
686 path: Option<Arc<Path>>,
687 _subscriptions: Vec<Subscription>,
688 telemetry: Option<Arc<Telemetry>>,
689 language_registry: Arc<LanguageRegistry>,
690 project: Option<Entity<Project>>,
691 prompt_builder: Arc<PromptBuilder>,
692 completion_mode: agent_settings::CompletionMode,
693}
694
695trait ContextAnnotation {
696 fn range(&self) -> &Range<language::Anchor>;
697}
698
699impl ContextAnnotation for ParsedSlashCommand {
700 fn range(&self) -> &Range<language::Anchor> {
701 &self.source_range
702 }
703}
704
705impl EventEmitter<TextThreadEvent> for TextThread {}
706
707impl TextThread {
708 pub fn local(
709 language_registry: Arc<LanguageRegistry>,
710 project: Option<Entity<Project>>,
711 telemetry: Option<Arc<Telemetry>>,
712 prompt_builder: Arc<PromptBuilder>,
713 slash_commands: Arc<SlashCommandWorkingSet>,
714 cx: &mut Context<Self>,
715 ) -> Self {
716 Self::new(
717 TextThreadId::new(),
718 ReplicaId::default(),
719 language::Capability::ReadWrite,
720 language_registry,
721 prompt_builder,
722 slash_commands,
723 project,
724 telemetry,
725 cx,
726 )
727 }
728
729 pub fn completion_mode(&self) -> agent_settings::CompletionMode {
730 self.completion_mode
731 }
732
733 pub fn set_completion_mode(&mut self, completion_mode: agent_settings::CompletionMode) {
734 self.completion_mode = completion_mode;
735 }
736
737 pub fn new(
738 id: TextThreadId,
739 replica_id: ReplicaId,
740 capability: language::Capability,
741 language_registry: Arc<LanguageRegistry>,
742 prompt_builder: Arc<PromptBuilder>,
743 slash_commands: Arc<SlashCommandWorkingSet>,
744 project: Option<Entity<Project>>,
745 telemetry: Option<Arc<Telemetry>>,
746 cx: &mut Context<Self>,
747 ) -> Self {
748 let buffer = cx.new(|_cx| {
749 let buffer = Buffer::remote(
750 language::BufferId::new(1).unwrap(),
751 replica_id,
752 capability,
753 "",
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::Started |
2078 LanguageModelCompletionEvent::Queued {..} |
2079 LanguageModelCompletionEvent::ToolUseLimitReached { .. } => {}
2080 LanguageModelCompletionEvent::UsageUpdated { amount, limit } => {
2081 this.update_model_request_usage(
2082 amount as u32,
2083 limit,
2084 cx,
2085 );
2086 }
2087 LanguageModelCompletionEvent::StartMessage { .. } => {}
2088 LanguageModelCompletionEvent::Stop(reason) => {
2089 stop_reason = reason;
2090 }
2091 LanguageModelCompletionEvent::Thinking { text: chunk, .. } => {
2092 if thought_process_stack.is_empty() {
2093 let start =
2094 buffer.anchor_before(message_old_end_offset);
2095 thought_process_stack.push(start);
2096 let chunk =
2097 format!("{THOUGHT_PROCESS_START_MARKER}{chunk}{THOUGHT_PROCESS_END_MARKER}");
2098 let chunk_len = chunk.len();
2099 buffer.edit(
2100 [(
2101 message_old_end_offset..message_old_end_offset,
2102 chunk,
2103 )],
2104 None,
2105 cx,
2106 );
2107 let end = buffer
2108 .anchor_before(message_old_end_offset + chunk_len);
2109 context_event = Some(
2110 TextThreadEvent::StartedThoughtProcess(start..end),
2111 );
2112 } else {
2113 // This ensures that all the thinking chunks are inserted inside the thinking tag
2114 let insertion_position =
2115 message_old_end_offset - THOUGHT_PROCESS_END_MARKER.len();
2116 buffer.edit(
2117 [(insertion_position..insertion_position, chunk)],
2118 None,
2119 cx,
2120 );
2121 }
2122 }
2123 LanguageModelCompletionEvent::RedactedThinking { .. } => {},
2124 LanguageModelCompletionEvent::Text(mut chunk) => {
2125 if let Some(start) = thought_process_stack.pop() {
2126 let end = buffer.anchor_before(message_old_end_offset);
2127 context_event =
2128 Some(TextThreadEvent::EndedThoughtProcess(end));
2129 thought_process_output_section =
2130 Some(ThoughtProcessOutputSection {
2131 range: start..end,
2132 });
2133 chunk.insert_str(0, "\n\n");
2134 }
2135
2136 buffer.edit(
2137 [(
2138 message_old_end_offset..message_old_end_offset,
2139 chunk,
2140 )],
2141 None,
2142 cx,
2143 );
2144 }
2145 LanguageModelCompletionEvent::ToolUse(_) |
2146 LanguageModelCompletionEvent::ToolUseJsonParseError { .. } |
2147 LanguageModelCompletionEvent::UsageUpdate(_) => {}
2148 }
2149 });
2150
2151 if let Some(section) = thought_process_output_section.take() {
2152 this.insert_thought_process_output_section(section, cx);
2153 }
2154 if let Some(context_event) = context_event.take() {
2155 cx.emit(context_event);
2156 }
2157
2158 cx.emit(TextThreadEvent::StreamedCompletion);
2159
2160 Some(())
2161 })?;
2162 smol::future::yield_now().await;
2163 }
2164 this.update(cx, |this, cx| {
2165 this.pending_completions
2166 .retain(|completion| completion.id != pending_completion_id);
2167 this.summarize(false, cx);
2168 this.update_cache_status_for_completion(cx);
2169 })?;
2170
2171 anyhow::Ok(stop_reason)
2172 };
2173
2174 let result = stream_completion.await;
2175
2176 this.update(cx, |this, cx| {
2177 let error_message = if let Some(error) = result.as_ref().err() {
2178 if error.is::<PaymentRequiredError>() {
2179 cx.emit(TextThreadEvent::ShowPaymentRequiredError);
2180 this.update_metadata(assistant_message_id, cx, |metadata| {
2181 metadata.status = MessageStatus::Canceled;
2182 });
2183 Some(error.to_string())
2184 } else {
2185 let error_message = error
2186 .chain()
2187 .map(|err| err.to_string())
2188 .collect::<Vec<_>>()
2189 .join("\n");
2190 cx.emit(TextThreadEvent::ShowAssistError(SharedString::from(
2191 error_message.clone(),
2192 )));
2193 this.update_metadata(assistant_message_id, cx, |metadata| {
2194 metadata.status =
2195 MessageStatus::Error(SharedString::from(error_message.clone()));
2196 });
2197 Some(error_message)
2198 }
2199 } else {
2200 this.update_metadata(assistant_message_id, cx, |metadata| {
2201 metadata.status = MessageStatus::Done;
2202 });
2203 None
2204 };
2205
2206 let language_name = this
2207 .buffer
2208 .read(cx)
2209 .language()
2210 .map(|language| language.name());
2211 report_assistant_event(
2212 AssistantEventData {
2213 conversation_id: Some(this.id.0.clone()),
2214 kind: AssistantKind::Panel,
2215 phase: AssistantPhase::Response,
2216 message_id: None,
2217 model: model.telemetry_id(),
2218 model_provider: model.provider_id().to_string(),
2219 response_latency,
2220 error_message,
2221 language_name: language_name.map(|name| name.to_proto()),
2222 },
2223 this.telemetry.clone(),
2224 cx.http_client(),
2225 model.api_key(cx),
2226 cx.background_executor(),
2227 );
2228
2229 if let Ok(stop_reason) = result {
2230 match stop_reason {
2231 StopReason::ToolUse => {}
2232 StopReason::EndTurn => {}
2233 StopReason::MaxTokens => {}
2234 StopReason::Refusal => {}
2235 }
2236 }
2237 })
2238 .ok();
2239 }
2240 });
2241
2242 self.pending_completions.push(PendingCompletion {
2243 id: pending_completion_id,
2244 assistant_message_id: assistant_message.id,
2245 _task: task,
2246 });
2247
2248 Some(user_message)
2249 }
2250
2251 pub fn to_xml(&self, cx: &App) -> String {
2252 let mut output = String::new();
2253 let buffer = self.buffer.read(cx);
2254 for message in self.messages(cx) {
2255 if message.status != MessageStatus::Done {
2256 continue;
2257 }
2258
2259 writeln!(&mut output, "<{}>", message.role).unwrap();
2260 for chunk in buffer.text_for_range(message.offset_range) {
2261 output.push_str(chunk);
2262 }
2263 if !output.ends_with('\n') {
2264 output.push('\n');
2265 }
2266 writeln!(&mut output, "</{}>", message.role).unwrap();
2267 }
2268 output
2269 }
2270
2271 pub fn to_completion_request(
2272 &self,
2273 model: Option<&Arc<dyn LanguageModel>>,
2274 cx: &App,
2275 ) -> LanguageModelRequest {
2276 let buffer = self.buffer.read(cx);
2277
2278 let mut contents = self.contents(cx).peekable();
2279
2280 fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2281 let text: String = buffer.text_for_range(range).collect();
2282 if text.trim().is_empty() {
2283 None
2284 } else {
2285 Some(text)
2286 }
2287 }
2288
2289 let mut completion_request = LanguageModelRequest {
2290 thread_id: None,
2291 prompt_id: None,
2292 intent: Some(CompletionIntent::UserPrompt),
2293 mode: None,
2294 messages: Vec::new(),
2295 tools: Vec::new(),
2296 tool_choice: None,
2297 stop: Vec::new(),
2298 temperature: model.and_then(|model| AgentSettings::temperature_for_model(model, cx)),
2299 thinking_allowed: true,
2300 };
2301 for message in self.messages(cx) {
2302 if message.status != MessageStatus::Done {
2303 continue;
2304 }
2305
2306 let mut offset = message.offset_range.start;
2307 let mut request_message = LanguageModelRequestMessage {
2308 role: message.role,
2309 content: Vec::new(),
2310 cache: message.cache.as_ref().is_some_and(|cache| cache.is_anchor),
2311 };
2312
2313 while let Some(content) = contents.peek() {
2314 if content
2315 .range()
2316 .end
2317 .cmp(&message.anchor_range.end, buffer)
2318 .is_lt()
2319 {
2320 let content = contents.next().unwrap();
2321 let range = content.range().to_offset(buffer);
2322 request_message.content.extend(
2323 collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2324 );
2325
2326 match content {
2327 Content::Image { image, .. } => {
2328 if let Some(image) = image.clone().now_or_never().flatten() {
2329 request_message
2330 .content
2331 .push(language_model::MessageContent::Image(image));
2332 }
2333 }
2334 }
2335
2336 offset = range.end;
2337 } else {
2338 break;
2339 }
2340 }
2341
2342 request_message.content.extend(
2343 collect_text_content(buffer, offset..message.offset_range.end)
2344 .map(MessageContent::Text),
2345 );
2346
2347 if !request_message.contents_empty() {
2348 completion_request.messages.push(request_message);
2349 }
2350 }
2351 let supports_burn_mode = if let Some(model) = model {
2352 model.supports_burn_mode()
2353 } else {
2354 false
2355 };
2356
2357 if supports_burn_mode {
2358 completion_request.mode = Some(self.completion_mode.into());
2359 }
2360 completion_request
2361 }
2362
2363 pub fn cancel_last_assist(&mut self, cx: &mut Context<Self>) -> bool {
2364 if let Some(pending_completion) = self.pending_completions.pop() {
2365 self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2366 if metadata.status == MessageStatus::Pending {
2367 metadata.status = MessageStatus::Canceled;
2368 }
2369 });
2370 true
2371 } else {
2372 false
2373 }
2374 }
2375
2376 pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2377 for id in &ids {
2378 if let Some(metadata) = self.messages_metadata.get(id) {
2379 let role = metadata.role.cycle();
2380 self.update_metadata(*id, cx, |metadata| metadata.role = role);
2381 }
2382 }
2383
2384 self.message_roles_updated(ids, cx);
2385 }
2386
2387 fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2388 let mut ranges = Vec::new();
2389 for message in self.messages(cx) {
2390 if ids.contains(&message.id) {
2391 ranges.push(message.anchor_range.clone());
2392 }
2393 }
2394 }
2395
2396 pub fn update_metadata(
2397 &mut self,
2398 id: MessageId,
2399 cx: &mut Context<Self>,
2400 f: impl FnOnce(&mut MessageMetadata),
2401 ) {
2402 let version = self.version.clone();
2403 let timestamp = self.next_timestamp();
2404 if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2405 f(metadata);
2406 metadata.timestamp = timestamp;
2407 let operation = TextThreadOperation::UpdateMessage {
2408 message_id: id,
2409 metadata: metadata.clone(),
2410 version,
2411 };
2412 self.push_op(operation, cx);
2413 cx.emit(TextThreadEvent::MessagesEdited);
2414 cx.notify();
2415 }
2416 }
2417
2418 pub fn insert_message_after(
2419 &mut self,
2420 message_id: MessageId,
2421 role: Role,
2422 status: MessageStatus,
2423 cx: &mut Context<Self>,
2424 ) -> Option<MessageAnchor> {
2425 if let Some(prev_message_ix) = self
2426 .message_anchors
2427 .iter()
2428 .position(|message| message.id == message_id)
2429 {
2430 // Find the next valid message after the one we were given.
2431 let mut next_message_ix = prev_message_ix + 1;
2432 while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2433 if next_message.start.is_valid(self.buffer.read(cx)) {
2434 break;
2435 }
2436 next_message_ix += 1;
2437 }
2438
2439 let buffer = self.buffer.read(cx);
2440 let offset = self
2441 .message_anchors
2442 .get(next_message_ix)
2443 .map_or(buffer.len(), |message| {
2444 buffer.clip_offset(message.start.to_previous_offset(buffer), Bias::Left)
2445 });
2446 Some(self.insert_message_at_offset(offset, role, status, cx))
2447 } else {
2448 None
2449 }
2450 }
2451
2452 fn insert_message_at_offset(
2453 &mut self,
2454 offset: usize,
2455 role: Role,
2456 status: MessageStatus,
2457 cx: &mut Context<Self>,
2458 ) -> MessageAnchor {
2459 let start = self.buffer.update(cx, |buffer, cx| {
2460 buffer.edit([(offset..offset, "\n")], None, cx);
2461 buffer.anchor_before(offset + 1)
2462 });
2463
2464 let version = self.version.clone();
2465 let anchor = MessageAnchor {
2466 id: MessageId(self.next_timestamp()),
2467 start,
2468 };
2469 let metadata = MessageMetadata {
2470 role,
2471 status,
2472 timestamp: anchor.id.0,
2473 cache: None,
2474 };
2475 self.insert_message(anchor.clone(), metadata.clone(), cx);
2476 self.push_op(
2477 TextThreadOperation::InsertMessage {
2478 anchor: anchor.clone(),
2479 metadata,
2480 version,
2481 },
2482 cx,
2483 );
2484 anchor
2485 }
2486
2487 pub fn insert_content(&mut self, content: Content, cx: &mut Context<Self>) {
2488 let buffer = self.buffer.read(cx);
2489 let insertion_ix = match self
2490 .contents
2491 .binary_search_by(|probe| probe.cmp(&content, buffer))
2492 {
2493 Ok(ix) => {
2494 self.contents.remove(ix);
2495 ix
2496 }
2497 Err(ix) => ix,
2498 };
2499 self.contents.insert(insertion_ix, content);
2500 cx.emit(TextThreadEvent::MessagesEdited);
2501 }
2502
2503 pub fn contents<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Content> {
2504 let buffer = self.buffer.read(cx);
2505 self.contents
2506 .iter()
2507 .filter(|content| {
2508 let range = content.range();
2509 range.start.is_valid(buffer) && range.end.is_valid(buffer)
2510 })
2511 .cloned()
2512 }
2513
2514 pub fn split_message(
2515 &mut self,
2516 range: Range<usize>,
2517 cx: &mut Context<Self>,
2518 ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2519 let start_message = self.message_for_offset(range.start, cx);
2520 let end_message = self.message_for_offset(range.end, cx);
2521 if let Some((start_message, end_message)) = start_message.zip(end_message) {
2522 // Prevent splitting when range spans multiple messages.
2523 if start_message.id != end_message.id {
2524 return (None, None);
2525 }
2526
2527 let message = start_message;
2528 let at_end = range.end >= message.offset_range.end.saturating_sub(1);
2529 let role_after = if range.start == range.end || at_end {
2530 Role::User
2531 } else {
2532 message.role
2533 };
2534 let role = message.role;
2535 let mut edited_buffer = false;
2536
2537 let mut suffix_start = None;
2538
2539 // TODO: why did this start panicking?
2540 if range.start > message.offset_range.start
2541 && range.end < message.offset_range.end.saturating_sub(1)
2542 {
2543 if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2544 suffix_start = Some(range.end + 1);
2545 } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2546 suffix_start = Some(range.end);
2547 }
2548 }
2549
2550 let version = self.version.clone();
2551 let suffix = if let Some(suffix_start) = suffix_start {
2552 MessageAnchor {
2553 id: MessageId(self.next_timestamp()),
2554 start: self.buffer.read(cx).anchor_before(suffix_start),
2555 }
2556 } else {
2557 self.buffer.update(cx, |buffer, cx| {
2558 buffer.edit([(range.end..range.end, "\n")], None, cx);
2559 });
2560 edited_buffer = true;
2561 MessageAnchor {
2562 id: MessageId(self.next_timestamp()),
2563 start: self.buffer.read(cx).anchor_before(range.end + 1),
2564 }
2565 };
2566
2567 let suffix_metadata = MessageMetadata {
2568 role: role_after,
2569 status: MessageStatus::Done,
2570 timestamp: suffix.id.0,
2571 cache: None,
2572 };
2573 self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2574 self.push_op(
2575 TextThreadOperation::InsertMessage {
2576 anchor: suffix.clone(),
2577 metadata: suffix_metadata,
2578 version,
2579 },
2580 cx,
2581 );
2582
2583 let new_messages =
2584 if range.start == range.end || range.start == message.offset_range.start {
2585 (None, Some(suffix))
2586 } else {
2587 let mut prefix_end = None;
2588 if range.start > message.offset_range.start
2589 && range.end < message.offset_range.end - 1
2590 {
2591 if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2592 prefix_end = Some(range.start + 1);
2593 } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2594 == Some('\n')
2595 {
2596 prefix_end = Some(range.start);
2597 }
2598 }
2599
2600 let version = self.version.clone();
2601 let selection = if let Some(prefix_end) = prefix_end {
2602 MessageAnchor {
2603 id: MessageId(self.next_timestamp()),
2604 start: self.buffer.read(cx).anchor_before(prefix_end),
2605 }
2606 } else {
2607 self.buffer.update(cx, |buffer, cx| {
2608 buffer.edit([(range.start..range.start, "\n")], None, cx)
2609 });
2610 edited_buffer = true;
2611 MessageAnchor {
2612 id: MessageId(self.next_timestamp()),
2613 start: self.buffer.read(cx).anchor_before(range.end + 1),
2614 }
2615 };
2616
2617 let selection_metadata = MessageMetadata {
2618 role,
2619 status: MessageStatus::Done,
2620 timestamp: selection.id.0,
2621 cache: None,
2622 };
2623 self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2624 self.push_op(
2625 TextThreadOperation::InsertMessage {
2626 anchor: selection.clone(),
2627 metadata: selection_metadata,
2628 version,
2629 },
2630 cx,
2631 );
2632
2633 (Some(selection), Some(suffix))
2634 };
2635
2636 if !edited_buffer {
2637 cx.emit(TextThreadEvent::MessagesEdited);
2638 }
2639 new_messages
2640 } else {
2641 (None, None)
2642 }
2643 }
2644
2645 fn insert_message(
2646 &mut self,
2647 new_anchor: MessageAnchor,
2648 new_metadata: MessageMetadata,
2649 cx: &mut Context<Self>,
2650 ) {
2651 cx.emit(TextThreadEvent::MessagesEdited);
2652
2653 self.messages_metadata.insert(new_anchor.id, new_metadata);
2654
2655 let buffer = self.buffer.read(cx);
2656 let insertion_ix = self
2657 .message_anchors
2658 .iter()
2659 .position(|anchor| {
2660 let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2661 comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2662 })
2663 .unwrap_or(self.message_anchors.len());
2664 self.message_anchors.insert(insertion_ix, new_anchor);
2665 }
2666
2667 pub fn summarize(&mut self, mut replace_old: bool, cx: &mut Context<Self>) {
2668 let Some(model) = LanguageModelRegistry::read_global(cx).thread_summary_model() else {
2669 return;
2670 };
2671
2672 if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_pending()) {
2673 if !model.provider.is_authenticated(cx) {
2674 return;
2675 }
2676
2677 let mut request = self.to_completion_request(Some(&model.model), cx);
2678 request.messages.push(LanguageModelRequestMessage {
2679 role: Role::User,
2680 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2681 cache: false,
2682 });
2683
2684 // If there is no summary, it is set with `done: false` so that "Loading Summary…" can
2685 // be displayed.
2686 match self.summary {
2687 TextThreadSummary::Pending | TextThreadSummary::Error => {
2688 self.summary = TextThreadSummary::Content(TextThreadSummaryContent {
2689 text: "".to_string(),
2690 done: false,
2691 timestamp: clock::Lamport::MIN,
2692 });
2693 replace_old = true;
2694 }
2695 TextThreadSummary::Content(_) => {}
2696 }
2697
2698 self.summary_task = cx.spawn(async move |this, cx| {
2699 let result = async {
2700 let stream = model.model.stream_completion_text(request, cx);
2701 let mut messages = stream.await?;
2702
2703 let mut replaced = !replace_old;
2704 while let Some(message) = messages.stream.next().await {
2705 let text = message?;
2706 let mut lines = text.lines();
2707 this.update(cx, |this, cx| {
2708 let version = this.version.clone();
2709 let timestamp = this.next_timestamp();
2710 let summary = this.summary.content_or_set_empty();
2711 if !replaced && replace_old {
2712 summary.text.clear();
2713 replaced = true;
2714 }
2715 summary.text.extend(lines.next());
2716 summary.timestamp = timestamp;
2717 let operation = TextThreadOperation::UpdateSummary {
2718 summary: summary.clone(),
2719 version,
2720 };
2721 this.push_op(operation, cx);
2722 cx.emit(TextThreadEvent::SummaryChanged);
2723 cx.emit(TextThreadEvent::SummaryGenerated);
2724 })?;
2725
2726 // Stop if the LLM generated multiple lines.
2727 if lines.next().is_some() {
2728 break;
2729 }
2730 }
2731
2732 this.read_with(cx, |this, _cx| {
2733 if let Some(summary) = this.summary.content()
2734 && summary.text.is_empty()
2735 {
2736 bail!("Model generated an empty summary");
2737 }
2738 Ok(())
2739 })??;
2740
2741 this.update(cx, |this, cx| {
2742 let version = this.version.clone();
2743 let timestamp = this.next_timestamp();
2744 if let Some(summary) = this.summary.content_as_mut() {
2745 summary.done = true;
2746 summary.timestamp = timestamp;
2747 let operation = TextThreadOperation::UpdateSummary {
2748 summary: summary.clone(),
2749 version,
2750 };
2751 this.push_op(operation, cx);
2752 cx.emit(TextThreadEvent::SummaryChanged);
2753 cx.emit(TextThreadEvent::SummaryGenerated);
2754 }
2755 })?;
2756
2757 anyhow::Ok(())
2758 }
2759 .await;
2760
2761 if let Err(err) = result {
2762 this.update(cx, |this, cx| {
2763 this.summary = TextThreadSummary::Error;
2764 cx.emit(TextThreadEvent::SummaryChanged);
2765 })
2766 .log_err();
2767 log::error!("Error generating context summary: {}", err);
2768 }
2769
2770 Some(())
2771 });
2772 }
2773 }
2774
2775 fn message_for_offset(&self, offset: usize, cx: &App) -> Option<Message> {
2776 self.messages_for_offsets([offset], cx).pop()
2777 }
2778
2779 pub fn messages_for_offsets(
2780 &self,
2781 offsets: impl IntoIterator<Item = usize>,
2782 cx: &App,
2783 ) -> Vec<Message> {
2784 let mut result = Vec::new();
2785
2786 let mut messages = self.messages(cx).peekable();
2787 let mut offsets = offsets.into_iter().peekable();
2788 let mut current_message = messages.next();
2789 while let Some(offset) = offsets.next() {
2790 // Locate the message that contains the offset.
2791 while current_message.as_ref().is_some_and(|message| {
2792 !message.offset_range.contains(&offset) && messages.peek().is_some()
2793 }) {
2794 current_message = messages.next();
2795 }
2796 let Some(message) = current_message.as_ref() else {
2797 break;
2798 };
2799
2800 // Skip offsets that are in the same message.
2801 while offsets.peek().is_some_and(|offset| {
2802 message.offset_range.contains(offset) || messages.peek().is_none()
2803 }) {
2804 offsets.next();
2805 }
2806
2807 result.push(message.clone());
2808 }
2809 result
2810 }
2811
2812 fn messages_from_anchors<'a>(
2813 &'a self,
2814 message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2815 cx: &'a App,
2816 ) -> impl 'a + Iterator<Item = Message> {
2817 let buffer = self.buffer.read(cx);
2818
2819 Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2820 }
2821
2822 pub fn messages<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Message> {
2823 self.messages_from_anchors(self.message_anchors.iter(), cx)
2824 }
2825
2826 pub fn messages_from_iters<'a>(
2827 buffer: &'a Buffer,
2828 metadata: &'a HashMap<MessageId, MessageMetadata>,
2829 messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2830 ) -> impl 'a + Iterator<Item = Message> {
2831 let mut messages = messages.peekable();
2832
2833 iter::from_fn(move || {
2834 if let Some((start_ix, message_anchor)) = messages.next() {
2835 let metadata = metadata.get(&message_anchor.id)?;
2836
2837 let message_start = message_anchor.start.to_offset(buffer);
2838 let mut message_end = None;
2839 let mut end_ix = start_ix;
2840 while let Some((_, next_message)) = messages.peek() {
2841 if next_message.start.is_valid(buffer) {
2842 message_end = Some(next_message.start);
2843 break;
2844 } else {
2845 end_ix += 1;
2846 messages.next();
2847 }
2848 }
2849 let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2850 let message_end = message_end_anchor.to_offset(buffer);
2851
2852 return Some(Message {
2853 index_range: start_ix..end_ix,
2854 offset_range: message_start..message_end,
2855 anchor_range: message_anchor.start..message_end_anchor,
2856 id: message_anchor.id,
2857 role: metadata.role,
2858 status: metadata.status.clone(),
2859 cache: metadata.cache.clone(),
2860 });
2861 }
2862 None
2863 })
2864 }
2865
2866 pub fn save(
2867 &mut self,
2868 debounce: Option<Duration>,
2869 fs: Arc<dyn Fs>,
2870 cx: &mut Context<TextThread>,
2871 ) {
2872 if self.replica_id() != ReplicaId::default() {
2873 // Prevent saving a remote context for now.
2874 return;
2875 }
2876
2877 self.pending_save = cx.spawn(async move |this, cx| {
2878 if let Some(debounce) = debounce {
2879 cx.background_executor().timer(debounce).await;
2880 }
2881
2882 let (old_path, summary) = this.read_with(cx, |this, _| {
2883 let path = this.path.clone();
2884 let summary = if let Some(summary) = this.summary.content() {
2885 if summary.done {
2886 Some(summary.text.clone())
2887 } else {
2888 None
2889 }
2890 } else {
2891 None
2892 };
2893 (path, summary)
2894 })?;
2895
2896 if let Some(summary) = summary {
2897 let context = this.read_with(cx, |this, cx| this.serialize(cx))?;
2898 let mut discriminant = 1;
2899 let mut new_path;
2900 loop {
2901 new_path = text_threads_dir().join(&format!(
2902 "{} - {}.zed.json",
2903 summary.trim(),
2904 discriminant
2905 ));
2906 if fs.is_file(&new_path).await {
2907 discriminant += 1;
2908 } else {
2909 break;
2910 }
2911 }
2912
2913 fs.create_dir(text_threads_dir().as_ref()).await?;
2914
2915 // rename before write ensures that only one file exists
2916 if let Some(old_path) = old_path.as_ref()
2917 && new_path.as_path() != old_path.as_ref()
2918 {
2919 fs.rename(
2920 old_path,
2921 &new_path,
2922 RenameOptions {
2923 overwrite: true,
2924 ignore_if_exists: true,
2925 },
2926 )
2927 .await?;
2928 }
2929
2930 // update path before write in case it fails
2931 this.update(cx, {
2932 let new_path: Arc<Path> = new_path.clone().into();
2933 move |this, cx| {
2934 this.path = Some(new_path.clone());
2935 cx.emit(TextThreadEvent::PathChanged { old_path, new_path });
2936 }
2937 })
2938 .ok();
2939
2940 fs.atomic_write(new_path, serde_json::to_string(&context).unwrap())
2941 .await?;
2942 }
2943
2944 Ok(())
2945 });
2946 }
2947
2948 pub fn set_custom_summary(&mut self, custom_summary: String, cx: &mut Context<Self>) {
2949 let timestamp = self.next_timestamp();
2950 let summary = self.summary.content_or_set_empty();
2951 summary.timestamp = timestamp;
2952 summary.done = true;
2953 summary.text = custom_summary;
2954 cx.emit(TextThreadEvent::SummaryChanged);
2955 }
2956
2957 fn update_model_request_usage(&self, amount: u32, limit: UsageLimit, cx: &mut App) {
2958 let Some(project) = &self.project else {
2959 return;
2960 };
2961 project.read(cx).user_store().update(cx, |user_store, cx| {
2962 user_store.update_model_request_usage(
2963 ModelRequestUsage(RequestUsage {
2964 amount: amount as i32,
2965 limit,
2966 }),
2967 cx,
2968 )
2969 });
2970 }
2971}
2972
2973#[derive(Debug, Default)]
2974pub struct TextThreadVersion {
2975 text_thread: clock::Global,
2976 buffer: clock::Global,
2977}
2978
2979impl TextThreadVersion {
2980 pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2981 Self {
2982 text_thread: language::proto::deserialize_version(&proto.context_version),
2983 buffer: language::proto::deserialize_version(&proto.buffer_version),
2984 }
2985 }
2986
2987 pub fn to_proto(&self, context_id: TextThreadId) -> proto::ContextVersion {
2988 proto::ContextVersion {
2989 context_id: context_id.to_proto(),
2990 context_version: language::proto::serialize_version(&self.text_thread),
2991 buffer_version: language::proto::serialize_version(&self.buffer),
2992 }
2993 }
2994}
2995
2996#[derive(Debug, Clone)]
2997pub struct ParsedSlashCommand {
2998 pub name: String,
2999 pub arguments: SmallVec<[String; 3]>,
3000 pub status: PendingSlashCommandStatus,
3001 pub source_range: Range<language::Anchor>,
3002}
3003
3004#[derive(Debug)]
3005pub struct InvokedSlashCommand {
3006 pub name: SharedString,
3007 pub range: Range<language::Anchor>,
3008 pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
3009 pub status: InvokedSlashCommandStatus,
3010 pub transaction: Option<language::TransactionId>,
3011 timestamp: clock::Lamport,
3012}
3013
3014#[derive(Debug)]
3015pub enum InvokedSlashCommandStatus {
3016 Running(Task<()>),
3017 Error(SharedString),
3018 Finished,
3019}
3020
3021#[derive(Debug, Clone)]
3022pub enum PendingSlashCommandStatus {
3023 Idle,
3024 Running { _task: Shared<Task<()>> },
3025 Error(String),
3026}
3027
3028#[derive(Debug, Clone)]
3029pub struct PendingToolUse {
3030 pub id: LanguageModelToolUseId,
3031 pub name: String,
3032 pub input: serde_json::Value,
3033 pub status: PendingToolUseStatus,
3034 pub source_range: Range<language::Anchor>,
3035}
3036
3037#[derive(Debug, Clone)]
3038pub enum PendingToolUseStatus {
3039 Idle,
3040 Running { _task: Shared<Task<()>> },
3041 Error(String),
3042}
3043
3044impl PendingToolUseStatus {
3045 pub fn is_idle(&self) -> bool {
3046 matches!(self, PendingToolUseStatus::Idle)
3047 }
3048}
3049
3050#[derive(Serialize, Deserialize)]
3051pub struct SavedMessage {
3052 pub id: MessageId,
3053 pub start: usize,
3054 pub metadata: MessageMetadata,
3055}
3056
3057#[derive(Serialize, Deserialize)]
3058pub struct SavedTextThread {
3059 pub id: Option<TextThreadId>,
3060 pub zed: String,
3061 pub version: String,
3062 pub text: String,
3063 pub messages: Vec<SavedMessage>,
3064 pub summary: String,
3065 pub slash_command_output_sections:
3066 Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3067 #[serde(default)]
3068 pub thought_process_output_sections: Vec<ThoughtProcessOutputSection<usize>>,
3069}
3070
3071impl SavedTextThread {
3072 pub const VERSION: &'static str = "0.4.0";
3073
3074 pub fn from_json(json: &str) -> Result<Self> {
3075 let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3076 match saved_context_json
3077 .get("version")
3078 .context("version not found")?
3079 {
3080 serde_json::Value::String(version) => match version.as_str() {
3081 SavedTextThread::VERSION => Ok(serde_json::from_value::<SavedTextThread>(
3082 saved_context_json,
3083 )?),
3084 SavedContextV0_3_0::VERSION => {
3085 let saved_context =
3086 serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3087 Ok(saved_context.upgrade())
3088 }
3089 SavedContextV0_2_0::VERSION => {
3090 let saved_context =
3091 serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3092 Ok(saved_context.upgrade())
3093 }
3094 SavedContextV0_1_0::VERSION => {
3095 let saved_context =
3096 serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3097 Ok(saved_context.upgrade())
3098 }
3099 _ => anyhow::bail!("unrecognized saved context version: {version:?}"),
3100 },
3101 _ => anyhow::bail!("version not found on saved context"),
3102 }
3103 }
3104
3105 fn into_ops(
3106 self,
3107 buffer: &Entity<Buffer>,
3108 cx: &mut Context<TextThread>,
3109 ) -> Vec<TextThreadOperation> {
3110 let mut operations = Vec::new();
3111 let mut version = clock::Global::new();
3112 let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3113
3114 let mut first_message_metadata = None;
3115 for message in self.messages {
3116 if message.id == MessageId(clock::Lamport::MIN) {
3117 first_message_metadata = Some(message.metadata);
3118 } else {
3119 operations.push(TextThreadOperation::InsertMessage {
3120 anchor: MessageAnchor {
3121 id: message.id,
3122 start: buffer.read(cx).anchor_before(message.start),
3123 },
3124 metadata: MessageMetadata {
3125 role: message.metadata.role,
3126 status: message.metadata.status,
3127 timestamp: message.metadata.timestamp,
3128 cache: None,
3129 },
3130 version: version.clone(),
3131 });
3132 version.observe(message.id.0);
3133 next_timestamp.observe(message.id.0);
3134 }
3135 }
3136
3137 if let Some(metadata) = first_message_metadata {
3138 let timestamp = next_timestamp.tick();
3139 operations.push(TextThreadOperation::UpdateMessage {
3140 message_id: MessageId(clock::Lamport::MIN),
3141 metadata: MessageMetadata {
3142 role: metadata.role,
3143 status: metadata.status,
3144 timestamp,
3145 cache: None,
3146 },
3147 version: version.clone(),
3148 });
3149 version.observe(timestamp);
3150 }
3151
3152 let buffer = buffer.read(cx);
3153 for section in self.slash_command_output_sections {
3154 let timestamp = next_timestamp.tick();
3155 operations.push(TextThreadOperation::SlashCommandOutputSectionAdded {
3156 timestamp,
3157 section: SlashCommandOutputSection {
3158 range: buffer.anchor_after(section.range.start)
3159 ..buffer.anchor_before(section.range.end),
3160 icon: section.icon,
3161 label: section.label,
3162 metadata: section.metadata,
3163 },
3164 version: version.clone(),
3165 });
3166
3167 version.observe(timestamp);
3168 }
3169
3170 for section in self.thought_process_output_sections {
3171 let timestamp = next_timestamp.tick();
3172 operations.push(TextThreadOperation::ThoughtProcessOutputSectionAdded {
3173 timestamp,
3174 section: ThoughtProcessOutputSection {
3175 range: buffer.anchor_after(section.range.start)
3176 ..buffer.anchor_before(section.range.end),
3177 },
3178 version: version.clone(),
3179 });
3180
3181 version.observe(timestamp);
3182 }
3183
3184 let timestamp = next_timestamp.tick();
3185 operations.push(TextThreadOperation::UpdateSummary {
3186 summary: TextThreadSummaryContent {
3187 text: self.summary,
3188 done: true,
3189 timestamp,
3190 },
3191 version: version.clone(),
3192 });
3193 version.observe(timestamp);
3194
3195 operations
3196 }
3197}
3198
3199#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3200struct SavedMessageIdPreV0_4_0(usize);
3201
3202#[derive(Serialize, Deserialize)]
3203struct SavedMessagePreV0_4_0 {
3204 id: SavedMessageIdPreV0_4_0,
3205 start: usize,
3206}
3207
3208#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3209struct SavedMessageMetadataPreV0_4_0 {
3210 role: Role,
3211 status: MessageStatus,
3212}
3213
3214#[derive(Serialize, Deserialize)]
3215struct SavedContextV0_3_0 {
3216 id: Option<TextThreadId>,
3217 zed: String,
3218 version: String,
3219 text: String,
3220 messages: Vec<SavedMessagePreV0_4_0>,
3221 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3222 summary: String,
3223 slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3224}
3225
3226impl SavedContextV0_3_0 {
3227 const VERSION: &'static str = "0.3.0";
3228
3229 fn upgrade(self) -> SavedTextThread {
3230 SavedTextThread {
3231 id: self.id,
3232 zed: self.zed,
3233 version: SavedTextThread::VERSION.into(),
3234 text: self.text,
3235 messages: self
3236 .messages
3237 .into_iter()
3238 .filter_map(|message| {
3239 let metadata = self.message_metadata.get(&message.id)?;
3240 let timestamp = clock::Lamport {
3241 replica_id: ReplicaId::default(),
3242 value: message.id.0 as u32,
3243 };
3244 Some(SavedMessage {
3245 id: MessageId(timestamp),
3246 start: message.start,
3247 metadata: MessageMetadata {
3248 role: metadata.role,
3249 status: metadata.status.clone(),
3250 timestamp,
3251 cache: None,
3252 },
3253 })
3254 })
3255 .collect(),
3256 summary: self.summary,
3257 slash_command_output_sections: self.slash_command_output_sections,
3258 thought_process_output_sections: Vec::new(),
3259 }
3260 }
3261}
3262
3263#[derive(Serialize, Deserialize)]
3264struct SavedContextV0_2_0 {
3265 id: Option<TextThreadId>,
3266 zed: String,
3267 version: String,
3268 text: String,
3269 messages: Vec<SavedMessagePreV0_4_0>,
3270 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3271 summary: String,
3272}
3273
3274impl SavedContextV0_2_0 {
3275 const VERSION: &'static str = "0.2.0";
3276
3277 fn upgrade(self) -> SavedTextThread {
3278 SavedContextV0_3_0 {
3279 id: self.id,
3280 zed: self.zed,
3281 version: SavedContextV0_3_0::VERSION.to_string(),
3282 text: self.text,
3283 messages: self.messages,
3284 message_metadata: self.message_metadata,
3285 summary: self.summary,
3286 slash_command_output_sections: Vec::new(),
3287 }
3288 .upgrade()
3289 }
3290}
3291
3292#[derive(Serialize, Deserialize)]
3293struct SavedContextV0_1_0 {
3294 id: Option<TextThreadId>,
3295 zed: String,
3296 version: String,
3297 text: String,
3298 messages: Vec<SavedMessagePreV0_4_0>,
3299 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3300 summary: String,
3301 api_url: Option<String>,
3302 model: OpenAiModel,
3303}
3304
3305impl SavedContextV0_1_0 {
3306 const VERSION: &'static str = "0.1.0";
3307
3308 fn upgrade(self) -> SavedTextThread {
3309 SavedContextV0_2_0 {
3310 id: self.id,
3311 zed: self.zed,
3312 version: SavedContextV0_2_0::VERSION.to_string(),
3313 text: self.text,
3314 messages: self.messages,
3315 message_metadata: self.message_metadata,
3316 summary: self.summary,
3317 }
3318 .upgrade()
3319 }
3320}
3321
3322#[derive(Debug, Clone)]
3323pub struct SavedTextThreadMetadata {
3324 pub title: SharedString,
3325 pub path: Arc<Path>,
3326 pub mtime: chrono::DateTime<chrono::Local>,
3327}