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