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