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