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