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(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 messages: Vec::new(),
2559 tools: Vec::new(),
2560 stop: Vec::new(),
2561 temperature: None,
2562 };
2563 for message in self.messages(cx) {
2564 if message.status != MessageStatus::Done {
2565 continue;
2566 }
2567
2568 let mut offset = message.offset_range.start;
2569 let mut request_message = LanguageModelRequestMessage {
2570 role: message.role,
2571 content: Vec::new(),
2572 cache: message
2573 .cache
2574 .as_ref()
2575 .map_or(false, |cache| cache.is_anchor),
2576 };
2577
2578 while let Some(content) = contents.peek() {
2579 if content
2580 .range()
2581 .end
2582 .cmp(&message.anchor_range.end, buffer)
2583 .is_lt()
2584 {
2585 let content = contents.next().unwrap();
2586 let range = content.range().to_offset(buffer);
2587 request_message.content.extend(
2588 collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2589 );
2590
2591 match content {
2592 Content::Image { image, .. } => {
2593 if let Some(image) = image.clone().now_or_never().flatten() {
2594 request_message
2595 .content
2596 .push(language_model::MessageContent::Image(image));
2597 }
2598 }
2599 }
2600
2601 offset = range.end;
2602 } else {
2603 break;
2604 }
2605 }
2606
2607 request_message.content.extend(
2608 collect_text_content(buffer, offset..message.offset_range.end)
2609 .map(MessageContent::Text),
2610 );
2611
2612 completion_request.messages.push(request_message);
2613 }
2614
2615 if let RequestType::SuggestEdits = request_type {
2616 if let Ok(preamble) = self.prompt_builder.generate_suggest_edits_prompt() {
2617 let last_elem_index = completion_request.messages.len();
2618
2619 completion_request
2620 .messages
2621 .push(LanguageModelRequestMessage {
2622 role: Role::User,
2623 content: vec![MessageContent::Text(preamble)],
2624 cache: false,
2625 });
2626
2627 // The preamble message should be sent right before the last actual user message.
2628 completion_request
2629 .messages
2630 .swap(last_elem_index, last_elem_index.saturating_sub(1));
2631 }
2632 }
2633
2634 completion_request
2635 }
2636
2637 pub fn cancel_last_assist(&mut self, cx: &mut Context<Self>) -> bool {
2638 if let Some(pending_completion) = self.pending_completions.pop() {
2639 self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2640 if metadata.status == MessageStatus::Pending {
2641 metadata.status = MessageStatus::Canceled;
2642 }
2643 });
2644 true
2645 } else {
2646 false
2647 }
2648 }
2649
2650 pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2651 for id in &ids {
2652 if let Some(metadata) = self.messages_metadata.get(id) {
2653 let role = metadata.role.cycle();
2654 self.update_metadata(*id, cx, |metadata| metadata.role = role);
2655 }
2656 }
2657
2658 self.message_roles_updated(ids, cx);
2659 }
2660
2661 fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2662 let mut ranges = Vec::new();
2663 for message in self.messages(cx) {
2664 if ids.contains(&message.id) {
2665 ranges.push(message.anchor_range.clone());
2666 }
2667 }
2668
2669 let buffer = self.buffer.read(cx).text_snapshot();
2670 let mut updated = Vec::new();
2671 let mut removed = Vec::new();
2672 for range in ranges {
2673 self.reparse_patches_in_range(range, &buffer, &mut updated, &mut removed, cx);
2674 }
2675
2676 if !updated.is_empty() || !removed.is_empty() {
2677 cx.emit(ContextEvent::PatchesUpdated { removed, updated })
2678 }
2679 }
2680
2681 pub fn update_metadata(
2682 &mut self,
2683 id: MessageId,
2684 cx: &mut Context<Self>,
2685 f: impl FnOnce(&mut MessageMetadata),
2686 ) {
2687 let version = self.version.clone();
2688 let timestamp = self.next_timestamp();
2689 if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2690 f(metadata);
2691 metadata.timestamp = timestamp;
2692 let operation = ContextOperation::UpdateMessage {
2693 message_id: id,
2694 metadata: metadata.clone(),
2695 version,
2696 };
2697 self.push_op(operation, cx);
2698 cx.emit(ContextEvent::MessagesEdited);
2699 cx.notify();
2700 }
2701 }
2702
2703 pub fn insert_message_after(
2704 &mut self,
2705 message_id: MessageId,
2706 role: Role,
2707 status: MessageStatus,
2708 cx: &mut Context<Self>,
2709 ) -> Option<MessageAnchor> {
2710 if let Some(prev_message_ix) = self
2711 .message_anchors
2712 .iter()
2713 .position(|message| message.id == message_id)
2714 {
2715 // Find the next valid message after the one we were given.
2716 let mut next_message_ix = prev_message_ix + 1;
2717 while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2718 if next_message.start.is_valid(self.buffer.read(cx)) {
2719 break;
2720 }
2721 next_message_ix += 1;
2722 }
2723
2724 let buffer = self.buffer.read(cx);
2725 let offset = self
2726 .message_anchors
2727 .get(next_message_ix)
2728 .map_or(buffer.len(), |message| {
2729 buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
2730 });
2731 Some(self.insert_message_at_offset(offset, role, status, cx))
2732 } else {
2733 None
2734 }
2735 }
2736
2737 fn insert_message_at_offset(
2738 &mut self,
2739 offset: usize,
2740 role: Role,
2741 status: MessageStatus,
2742 cx: &mut Context<Self>,
2743 ) -> MessageAnchor {
2744 let start = self.buffer.update(cx, |buffer, cx| {
2745 buffer.edit([(offset..offset, "\n")], None, cx);
2746 buffer.anchor_before(offset + 1)
2747 });
2748
2749 let version = self.version.clone();
2750 let anchor = MessageAnchor {
2751 id: MessageId(self.next_timestamp()),
2752 start,
2753 };
2754 let metadata = MessageMetadata {
2755 role,
2756 status,
2757 timestamp: anchor.id.0,
2758 cache: None,
2759 };
2760 self.insert_message(anchor.clone(), metadata.clone(), cx);
2761 self.push_op(
2762 ContextOperation::InsertMessage {
2763 anchor: anchor.clone(),
2764 metadata,
2765 version,
2766 },
2767 cx,
2768 );
2769 anchor
2770 }
2771
2772 pub fn insert_content(&mut self, content: Content, cx: &mut Context<Self>) {
2773 let buffer = self.buffer.read(cx);
2774 let insertion_ix = match self
2775 .contents
2776 .binary_search_by(|probe| probe.cmp(&content, buffer))
2777 {
2778 Ok(ix) => {
2779 self.contents.remove(ix);
2780 ix
2781 }
2782 Err(ix) => ix,
2783 };
2784 self.contents.insert(insertion_ix, content);
2785 cx.emit(ContextEvent::MessagesEdited);
2786 }
2787
2788 pub fn contents<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Content> {
2789 let buffer = self.buffer.read(cx);
2790 self.contents
2791 .iter()
2792 .filter(|content| {
2793 let range = content.range();
2794 range.start.is_valid(buffer) && range.end.is_valid(buffer)
2795 })
2796 .cloned()
2797 }
2798
2799 pub fn split_message(
2800 &mut self,
2801 range: Range<usize>,
2802 cx: &mut Context<Self>,
2803 ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2804 let start_message = self.message_for_offset(range.start, cx);
2805 let end_message = self.message_for_offset(range.end, cx);
2806 if let Some((start_message, end_message)) = start_message.zip(end_message) {
2807 // Prevent splitting when range spans multiple messages.
2808 if start_message.id != end_message.id {
2809 return (None, None);
2810 }
2811
2812 let message = start_message;
2813 let role = message.role;
2814 let mut edited_buffer = false;
2815
2816 let mut suffix_start = None;
2817
2818 // TODO: why did this start panicking?
2819 if range.start > message.offset_range.start
2820 && range.end < message.offset_range.end.saturating_sub(1)
2821 {
2822 if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2823 suffix_start = Some(range.end + 1);
2824 } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2825 suffix_start = Some(range.end);
2826 }
2827 }
2828
2829 let version = self.version.clone();
2830 let suffix = if let Some(suffix_start) = suffix_start {
2831 MessageAnchor {
2832 id: MessageId(self.next_timestamp()),
2833 start: self.buffer.read(cx).anchor_before(suffix_start),
2834 }
2835 } else {
2836 self.buffer.update(cx, |buffer, cx| {
2837 buffer.edit([(range.end..range.end, "\n")], None, cx);
2838 });
2839 edited_buffer = true;
2840 MessageAnchor {
2841 id: MessageId(self.next_timestamp()),
2842 start: self.buffer.read(cx).anchor_before(range.end + 1),
2843 }
2844 };
2845
2846 let suffix_metadata = MessageMetadata {
2847 role,
2848 status: MessageStatus::Done,
2849 timestamp: suffix.id.0,
2850 cache: None,
2851 };
2852 self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2853 self.push_op(
2854 ContextOperation::InsertMessage {
2855 anchor: suffix.clone(),
2856 metadata: suffix_metadata,
2857 version,
2858 },
2859 cx,
2860 );
2861
2862 let new_messages =
2863 if range.start == range.end || range.start == message.offset_range.start {
2864 (None, Some(suffix))
2865 } else {
2866 let mut prefix_end = None;
2867 if range.start > message.offset_range.start
2868 && range.end < message.offset_range.end - 1
2869 {
2870 if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2871 prefix_end = Some(range.start + 1);
2872 } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2873 == Some('\n')
2874 {
2875 prefix_end = Some(range.start);
2876 }
2877 }
2878
2879 let version = self.version.clone();
2880 let selection = if let Some(prefix_end) = prefix_end {
2881 MessageAnchor {
2882 id: MessageId(self.next_timestamp()),
2883 start: self.buffer.read(cx).anchor_before(prefix_end),
2884 }
2885 } else {
2886 self.buffer.update(cx, |buffer, cx| {
2887 buffer.edit([(range.start..range.start, "\n")], None, cx)
2888 });
2889 edited_buffer = true;
2890 MessageAnchor {
2891 id: MessageId(self.next_timestamp()),
2892 start: self.buffer.read(cx).anchor_before(range.end + 1),
2893 }
2894 };
2895
2896 let selection_metadata = MessageMetadata {
2897 role,
2898 status: MessageStatus::Done,
2899 timestamp: selection.id.0,
2900 cache: None,
2901 };
2902 self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2903 self.push_op(
2904 ContextOperation::InsertMessage {
2905 anchor: selection.clone(),
2906 metadata: selection_metadata,
2907 version,
2908 },
2909 cx,
2910 );
2911
2912 (Some(selection), Some(suffix))
2913 };
2914
2915 if !edited_buffer {
2916 cx.emit(ContextEvent::MessagesEdited);
2917 }
2918 new_messages
2919 } else {
2920 (None, None)
2921 }
2922 }
2923
2924 fn insert_message(
2925 &mut self,
2926 new_anchor: MessageAnchor,
2927 new_metadata: MessageMetadata,
2928 cx: &mut Context<Self>,
2929 ) {
2930 cx.emit(ContextEvent::MessagesEdited);
2931
2932 self.messages_metadata.insert(new_anchor.id, new_metadata);
2933
2934 let buffer = self.buffer.read(cx);
2935 let insertion_ix = self
2936 .message_anchors
2937 .iter()
2938 .position(|anchor| {
2939 let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2940 comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2941 })
2942 .unwrap_or(self.message_anchors.len());
2943 self.message_anchors.insert(insertion_ix, new_anchor);
2944 }
2945
2946 pub fn summarize(&mut self, replace_old: bool, cx: &mut Context<Self>) {
2947 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
2948 return;
2949 };
2950
2951 if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
2952 if !model.provider.is_authenticated(cx) {
2953 return;
2954 }
2955
2956 let mut request = self.to_completion_request(RequestType::Chat, cx);
2957 request.messages.push(LanguageModelRequestMessage {
2958 role: Role::User,
2959 content: vec![
2960 "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:`"
2961 .into(),
2962 ],
2963 cache: false,
2964 });
2965
2966 self.pending_summary = cx.spawn(async move |this, cx| {
2967 async move {
2968 let stream = model.model.stream_completion_text(request, &cx);
2969 let mut messages = stream.await?;
2970
2971 let mut replaced = !replace_old;
2972 while let Some(message) = messages.stream.next().await {
2973 let text = message?;
2974 let mut lines = text.lines();
2975 this.update(cx, |this, cx| {
2976 let version = this.version.clone();
2977 let timestamp = this.next_timestamp();
2978 let summary = this.summary.get_or_insert(ContextSummary::default());
2979 if !replaced && replace_old {
2980 summary.text.clear();
2981 replaced = true;
2982 }
2983 summary.text.extend(lines.next());
2984 summary.timestamp = timestamp;
2985 let operation = ContextOperation::UpdateSummary {
2986 summary: summary.clone(),
2987 version,
2988 };
2989 this.push_op(operation, cx);
2990 cx.emit(ContextEvent::SummaryChanged);
2991 })?;
2992
2993 // Stop if the LLM generated multiple lines.
2994 if lines.next().is_some() {
2995 break;
2996 }
2997 }
2998
2999 this.update(cx, |this, cx| {
3000 let version = this.version.clone();
3001 let timestamp = this.next_timestamp();
3002 if let Some(summary) = this.summary.as_mut() {
3003 summary.done = true;
3004 summary.timestamp = timestamp;
3005 let operation = ContextOperation::UpdateSummary {
3006 summary: summary.clone(),
3007 version,
3008 };
3009 this.push_op(operation, cx);
3010 cx.emit(ContextEvent::SummaryChanged);
3011 }
3012 })?;
3013
3014 anyhow::Ok(())
3015 }
3016 .log_err()
3017 .await
3018 });
3019 }
3020 }
3021
3022 fn message_for_offset(&self, offset: usize, cx: &App) -> Option<Message> {
3023 self.messages_for_offsets([offset], cx).pop()
3024 }
3025
3026 pub fn messages_for_offsets(
3027 &self,
3028 offsets: impl IntoIterator<Item = usize>,
3029 cx: &App,
3030 ) -> Vec<Message> {
3031 let mut result = Vec::new();
3032
3033 let mut messages = self.messages(cx).peekable();
3034 let mut offsets = offsets.into_iter().peekable();
3035 let mut current_message = messages.next();
3036 while let Some(offset) = offsets.next() {
3037 // Locate the message that contains the offset.
3038 while current_message.as_ref().map_or(false, |message| {
3039 !message.offset_range.contains(&offset) && messages.peek().is_some()
3040 }) {
3041 current_message = messages.next();
3042 }
3043 let Some(message) = current_message.as_ref() else {
3044 break;
3045 };
3046
3047 // Skip offsets that are in the same message.
3048 while offsets.peek().map_or(false, |offset| {
3049 message.offset_range.contains(offset) || messages.peek().is_none()
3050 }) {
3051 offsets.next();
3052 }
3053
3054 result.push(message.clone());
3055 }
3056 result
3057 }
3058
3059 fn messages_from_anchors<'a>(
3060 &'a self,
3061 message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
3062 cx: &'a App,
3063 ) -> impl 'a + Iterator<Item = Message> {
3064 let buffer = self.buffer.read(cx);
3065
3066 Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
3067 }
3068
3069 pub fn messages<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Message> {
3070 self.messages_from_anchors(self.message_anchors.iter(), cx)
3071 }
3072
3073 pub fn messages_from_iters<'a>(
3074 buffer: &'a Buffer,
3075 metadata: &'a HashMap<MessageId, MessageMetadata>,
3076 messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
3077 ) -> impl 'a + Iterator<Item = Message> {
3078 let mut messages = messages.peekable();
3079
3080 iter::from_fn(move || {
3081 if let Some((start_ix, message_anchor)) = messages.next() {
3082 let metadata = metadata.get(&message_anchor.id)?;
3083
3084 let message_start = message_anchor.start.to_offset(buffer);
3085 let mut message_end = None;
3086 let mut end_ix = start_ix;
3087 while let Some((_, next_message)) = messages.peek() {
3088 if next_message.start.is_valid(buffer) {
3089 message_end = Some(next_message.start);
3090 break;
3091 } else {
3092 end_ix += 1;
3093 messages.next();
3094 }
3095 }
3096 let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
3097 let message_end = message_end_anchor.to_offset(buffer);
3098
3099 return Some(Message {
3100 index_range: start_ix..end_ix,
3101 offset_range: message_start..message_end,
3102 anchor_range: message_anchor.start..message_end_anchor,
3103 id: message_anchor.id,
3104 role: metadata.role,
3105 status: metadata.status.clone(),
3106 cache: metadata.cache.clone(),
3107 });
3108 }
3109 None
3110 })
3111 }
3112
3113 pub fn save(
3114 &mut self,
3115 debounce: Option<Duration>,
3116 fs: Arc<dyn Fs>,
3117 cx: &mut Context<AssistantContext>,
3118 ) {
3119 if self.replica_id() != ReplicaId::default() {
3120 // Prevent saving a remote context for now.
3121 return;
3122 }
3123
3124 self.pending_save = cx.spawn(async move |this, cx| {
3125 if let Some(debounce) = debounce {
3126 cx.background_executor().timer(debounce).await;
3127 }
3128
3129 let (old_path, summary) = this.read_with(cx, |this, _| {
3130 let path = this.path.clone();
3131 let summary = if let Some(summary) = this.summary.as_ref() {
3132 if summary.done {
3133 Some(summary.text.clone())
3134 } else {
3135 None
3136 }
3137 } else {
3138 None
3139 };
3140 (path, summary)
3141 })?;
3142
3143 if let Some(summary) = summary {
3144 let context = this.read_with(cx, |this, cx| this.serialize(cx))?;
3145 let mut discriminant = 1;
3146 let mut new_path;
3147 loop {
3148 new_path = contexts_dir().join(&format!(
3149 "{} - {}.zed.json",
3150 summary.trim(),
3151 discriminant
3152 ));
3153 if fs.is_file(&new_path).await {
3154 discriminant += 1;
3155 } else {
3156 break;
3157 }
3158 }
3159
3160 fs.create_dir(contexts_dir().as_ref()).await?;
3161 fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
3162 .await?;
3163 if let Some(old_path) = old_path {
3164 if new_path != old_path {
3165 fs.remove_file(
3166 &old_path,
3167 RemoveOptions {
3168 recursive: false,
3169 ignore_if_not_exists: true,
3170 },
3171 )
3172 .await?;
3173 }
3174 }
3175
3176 this.update(cx, |this, _| this.path = Some(new_path))?;
3177 }
3178
3179 Ok(())
3180 });
3181 }
3182
3183 pub fn custom_summary(&mut self, custom_summary: String, cx: &mut Context<Self>) {
3184 let timestamp = self.next_timestamp();
3185 let summary = self.summary.get_or_insert(ContextSummary::default());
3186 summary.timestamp = timestamp;
3187 summary.done = true;
3188 summary.text = custom_summary;
3189 cx.emit(ContextEvent::SummaryChanged);
3190 }
3191}
3192
3193fn trimmed_text_in_range(buffer: &BufferSnapshot, range: Range<text::Anchor>) -> String {
3194 let mut is_start = true;
3195 let mut content = buffer
3196 .text_for_range(range)
3197 .map(|mut chunk| {
3198 if is_start {
3199 chunk = chunk.trim_start_matches('\n');
3200 if !chunk.is_empty() {
3201 is_start = false;
3202 }
3203 }
3204 chunk
3205 })
3206 .collect::<String>();
3207 content.truncate(content.trim_end().len());
3208 content
3209}
3210
3211#[derive(Debug, Default)]
3212pub struct ContextVersion {
3213 context: clock::Global,
3214 buffer: clock::Global,
3215}
3216
3217impl ContextVersion {
3218 pub fn from_proto(proto: &proto::ContextVersion) -> Self {
3219 Self {
3220 context: language::proto::deserialize_version(&proto.context_version),
3221 buffer: language::proto::deserialize_version(&proto.buffer_version),
3222 }
3223 }
3224
3225 pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
3226 proto::ContextVersion {
3227 context_id: context_id.to_proto(),
3228 context_version: language::proto::serialize_version(&self.context),
3229 buffer_version: language::proto::serialize_version(&self.buffer),
3230 }
3231 }
3232}
3233
3234#[derive(Debug, Clone)]
3235pub struct ParsedSlashCommand {
3236 pub name: String,
3237 pub arguments: SmallVec<[String; 3]>,
3238 pub status: PendingSlashCommandStatus,
3239 pub source_range: Range<language::Anchor>,
3240}
3241
3242#[derive(Debug)]
3243pub struct InvokedSlashCommand {
3244 pub name: SharedString,
3245 pub range: Range<language::Anchor>,
3246 pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
3247 pub status: InvokedSlashCommandStatus,
3248 pub transaction: Option<language::TransactionId>,
3249 timestamp: clock::Lamport,
3250}
3251
3252#[derive(Debug)]
3253pub enum InvokedSlashCommandStatus {
3254 Running(Task<()>),
3255 Error(SharedString),
3256 Finished,
3257}
3258
3259#[derive(Debug, Clone)]
3260pub enum PendingSlashCommandStatus {
3261 Idle,
3262 Running { _task: Shared<Task<()>> },
3263 Error(String),
3264}
3265
3266#[derive(Debug, Clone)]
3267pub struct PendingToolUse {
3268 pub id: LanguageModelToolUseId,
3269 pub name: String,
3270 pub input: serde_json::Value,
3271 pub status: PendingToolUseStatus,
3272 pub source_range: Range<language::Anchor>,
3273}
3274
3275#[derive(Debug, Clone)]
3276pub enum PendingToolUseStatus {
3277 Idle,
3278 Running { _task: Shared<Task<()>> },
3279 Error(String),
3280}
3281
3282impl PendingToolUseStatus {
3283 pub fn is_idle(&self) -> bool {
3284 matches!(self, PendingToolUseStatus::Idle)
3285 }
3286}
3287
3288#[derive(Serialize, Deserialize)]
3289pub struct SavedMessage {
3290 pub id: MessageId,
3291 pub start: usize,
3292 pub metadata: MessageMetadata,
3293}
3294
3295#[derive(Serialize, Deserialize)]
3296pub struct SavedContext {
3297 pub id: Option<ContextId>,
3298 pub zed: String,
3299 pub version: String,
3300 pub text: String,
3301 pub messages: Vec<SavedMessage>,
3302 pub summary: String,
3303 pub slash_command_output_sections:
3304 Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3305 #[serde(default)]
3306 pub thought_process_output_sections: Vec<ThoughtProcessOutputSection<usize>>,
3307}
3308
3309impl SavedContext {
3310 pub const VERSION: &'static str = "0.4.0";
3311
3312 pub fn from_json(json: &str) -> Result<Self> {
3313 let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3314 match saved_context_json
3315 .get("version")
3316 .ok_or_else(|| anyhow!("version not found"))?
3317 {
3318 serde_json::Value::String(version) => match version.as_str() {
3319 SavedContext::VERSION => {
3320 Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
3321 }
3322 SavedContextV0_3_0::VERSION => {
3323 let saved_context =
3324 serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3325 Ok(saved_context.upgrade())
3326 }
3327 SavedContextV0_2_0::VERSION => {
3328 let saved_context =
3329 serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3330 Ok(saved_context.upgrade())
3331 }
3332 SavedContextV0_1_0::VERSION => {
3333 let saved_context =
3334 serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3335 Ok(saved_context.upgrade())
3336 }
3337 _ => Err(anyhow!("unrecognized saved context version: {}", version)),
3338 },
3339 _ => Err(anyhow!("version not found on saved context")),
3340 }
3341 }
3342
3343 fn into_ops(
3344 self,
3345 buffer: &Entity<Buffer>,
3346 cx: &mut Context<AssistantContext>,
3347 ) -> Vec<ContextOperation> {
3348 let mut operations = Vec::new();
3349 let mut version = clock::Global::new();
3350 let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3351
3352 let mut first_message_metadata = None;
3353 for message in self.messages {
3354 if message.id == MessageId(clock::Lamport::default()) {
3355 first_message_metadata = Some(message.metadata);
3356 } else {
3357 operations.push(ContextOperation::InsertMessage {
3358 anchor: MessageAnchor {
3359 id: message.id,
3360 start: buffer.read(cx).anchor_before(message.start),
3361 },
3362 metadata: MessageMetadata {
3363 role: message.metadata.role,
3364 status: message.metadata.status,
3365 timestamp: message.metadata.timestamp,
3366 cache: None,
3367 },
3368 version: version.clone(),
3369 });
3370 version.observe(message.id.0);
3371 next_timestamp.observe(message.id.0);
3372 }
3373 }
3374
3375 if let Some(metadata) = first_message_metadata {
3376 let timestamp = next_timestamp.tick();
3377 operations.push(ContextOperation::UpdateMessage {
3378 message_id: MessageId(clock::Lamport::default()),
3379 metadata: MessageMetadata {
3380 role: metadata.role,
3381 status: metadata.status,
3382 timestamp,
3383 cache: None,
3384 },
3385 version: version.clone(),
3386 });
3387 version.observe(timestamp);
3388 }
3389
3390 let buffer = buffer.read(cx);
3391 for section in self.slash_command_output_sections {
3392 let timestamp = next_timestamp.tick();
3393 operations.push(ContextOperation::SlashCommandOutputSectionAdded {
3394 timestamp,
3395 section: SlashCommandOutputSection {
3396 range: buffer.anchor_after(section.range.start)
3397 ..buffer.anchor_before(section.range.end),
3398 icon: section.icon,
3399 label: section.label,
3400 metadata: section.metadata,
3401 },
3402 version: version.clone(),
3403 });
3404
3405 version.observe(timestamp);
3406 }
3407
3408 for section in self.thought_process_output_sections {
3409 let timestamp = next_timestamp.tick();
3410 operations.push(ContextOperation::ThoughtProcessOutputSectionAdded {
3411 timestamp,
3412 section: ThoughtProcessOutputSection {
3413 range: buffer.anchor_after(section.range.start)
3414 ..buffer.anchor_before(section.range.end),
3415 },
3416 version: version.clone(),
3417 });
3418
3419 version.observe(timestamp);
3420 }
3421
3422 let timestamp = next_timestamp.tick();
3423 operations.push(ContextOperation::UpdateSummary {
3424 summary: ContextSummary {
3425 text: self.summary,
3426 done: true,
3427 timestamp,
3428 },
3429 version: version.clone(),
3430 });
3431 version.observe(timestamp);
3432
3433 operations
3434 }
3435}
3436
3437#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3438struct SavedMessageIdPreV0_4_0(usize);
3439
3440#[derive(Serialize, Deserialize)]
3441struct SavedMessagePreV0_4_0 {
3442 id: SavedMessageIdPreV0_4_0,
3443 start: usize,
3444}
3445
3446#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3447struct SavedMessageMetadataPreV0_4_0 {
3448 role: Role,
3449 status: MessageStatus,
3450}
3451
3452#[derive(Serialize, Deserialize)]
3453struct SavedContextV0_3_0 {
3454 id: Option<ContextId>,
3455 zed: String,
3456 version: String,
3457 text: String,
3458 messages: Vec<SavedMessagePreV0_4_0>,
3459 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3460 summary: String,
3461 slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3462}
3463
3464impl SavedContextV0_3_0 {
3465 const VERSION: &'static str = "0.3.0";
3466
3467 fn upgrade(self) -> SavedContext {
3468 SavedContext {
3469 id: self.id,
3470 zed: self.zed,
3471 version: SavedContext::VERSION.into(),
3472 text: self.text,
3473 messages: self
3474 .messages
3475 .into_iter()
3476 .filter_map(|message| {
3477 let metadata = self.message_metadata.get(&message.id)?;
3478 let timestamp = clock::Lamport {
3479 replica_id: ReplicaId::default(),
3480 value: message.id.0 as u32,
3481 };
3482 Some(SavedMessage {
3483 id: MessageId(timestamp),
3484 start: message.start,
3485 metadata: MessageMetadata {
3486 role: metadata.role,
3487 status: metadata.status.clone(),
3488 timestamp,
3489 cache: None,
3490 },
3491 })
3492 })
3493 .collect(),
3494 summary: self.summary,
3495 slash_command_output_sections: self.slash_command_output_sections,
3496 thought_process_output_sections: Vec::new(),
3497 }
3498 }
3499}
3500
3501#[derive(Serialize, Deserialize)]
3502struct SavedContextV0_2_0 {
3503 id: Option<ContextId>,
3504 zed: String,
3505 version: String,
3506 text: String,
3507 messages: Vec<SavedMessagePreV0_4_0>,
3508 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3509 summary: String,
3510}
3511
3512impl SavedContextV0_2_0 {
3513 const VERSION: &'static str = "0.2.0";
3514
3515 fn upgrade(self) -> SavedContext {
3516 SavedContextV0_3_0 {
3517 id: self.id,
3518 zed: self.zed,
3519 version: SavedContextV0_3_0::VERSION.to_string(),
3520 text: self.text,
3521 messages: self.messages,
3522 message_metadata: self.message_metadata,
3523 summary: self.summary,
3524 slash_command_output_sections: Vec::new(),
3525 }
3526 .upgrade()
3527 }
3528}
3529
3530#[derive(Serialize, Deserialize)]
3531struct SavedContextV0_1_0 {
3532 id: Option<ContextId>,
3533 zed: String,
3534 version: String,
3535 text: String,
3536 messages: Vec<SavedMessagePreV0_4_0>,
3537 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3538 summary: String,
3539 api_url: Option<String>,
3540 model: OpenAiModel,
3541}
3542
3543impl SavedContextV0_1_0 {
3544 const VERSION: &'static str = "0.1.0";
3545
3546 fn upgrade(self) -> SavedContext {
3547 SavedContextV0_2_0 {
3548 id: self.id,
3549 zed: self.zed,
3550 version: SavedContextV0_2_0::VERSION.to_string(),
3551 text: self.text,
3552 messages: self.messages,
3553 message_metadata: self.message_metadata,
3554 summary: self.summary,
3555 }
3556 .upgrade()
3557 }
3558}
3559
3560#[derive(Debug, Clone)]
3561pub struct SavedContextMetadata {
3562 pub title: String,
3563 pub path: PathBuf,
3564 pub mtime: chrono::DateTime<chrono::Local>,
3565}