1use crate::{
2 prompt_library::PromptStore, slash_command::SlashCommandLine, CompletionProvider, MessageId,
3 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| CompletionProvider::global(cx).count_tokens(request, cx))?
1128 .await?;
1129
1130 this.update(&mut cx, |this, cx| {
1131 this.token_count = Some(token_count);
1132 cx.notify()
1133 })?;
1134 anyhow::Ok(())
1135 }
1136 .log_err()
1137 });
1138 }
1139
1140 pub fn reparse_slash_commands(&mut self, cx: &mut ModelContext<Self>) {
1141 let buffer = self.buffer.read(cx);
1142 let mut row_ranges = self
1143 .edits_since_last_slash_command_parse
1144 .consume()
1145 .into_iter()
1146 .map(|edit| {
1147 let start_row = buffer.offset_to_point(edit.new.start).row;
1148 let end_row = buffer.offset_to_point(edit.new.end).row + 1;
1149 start_row..end_row
1150 })
1151 .peekable();
1152
1153 let mut removed = Vec::new();
1154 let mut updated = Vec::new();
1155 while let Some(mut row_range) = row_ranges.next() {
1156 while let Some(next_row_range) = row_ranges.peek() {
1157 if row_range.end >= next_row_range.start {
1158 row_range.end = next_row_range.end;
1159 row_ranges.next();
1160 } else {
1161 break;
1162 }
1163 }
1164
1165 let start = buffer.anchor_before(Point::new(row_range.start, 0));
1166 let end = buffer.anchor_after(Point::new(
1167 row_range.end - 1,
1168 buffer.line_len(row_range.end - 1),
1169 ));
1170
1171 let old_range = self.pending_command_indices_for_range(start..end, cx);
1172
1173 let mut new_commands = Vec::new();
1174 let mut lines = buffer.text_for_range(start..end).lines();
1175 let mut offset = lines.offset();
1176 while let Some(line) = lines.next() {
1177 if let Some(command_line) = SlashCommandLine::parse(line) {
1178 let name = &line[command_line.name.clone()];
1179 let argument = command_line.argument.as_ref().and_then(|argument| {
1180 (!argument.is_empty()).then_some(&line[argument.clone()])
1181 });
1182 if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1183 if !command.requires_argument() || argument.is_some() {
1184 let start_ix = offset + command_line.name.start - 1;
1185 let end_ix = offset
1186 + command_line
1187 .argument
1188 .map_or(command_line.name.end, |argument| argument.end);
1189 let source_range =
1190 buffer.anchor_after(start_ix)..buffer.anchor_after(end_ix);
1191 let pending_command = PendingSlashCommand {
1192 name: name.to_string(),
1193 argument: argument.map(ToString::to_string),
1194 source_range,
1195 status: PendingSlashCommandStatus::Idle,
1196 };
1197 updated.push(pending_command.clone());
1198 new_commands.push(pending_command);
1199 }
1200 }
1201 }
1202
1203 offset = lines.offset();
1204 }
1205
1206 let removed_commands = self.pending_slash_commands.splice(old_range, new_commands);
1207 removed.extend(removed_commands.map(|command| command.source_range));
1208 }
1209
1210 if !updated.is_empty() || !removed.is_empty() {
1211 cx.emit(ContextEvent::PendingSlashCommandsUpdated { removed, updated });
1212 }
1213 }
1214
1215 fn prune_invalid_edit_steps(&mut self, cx: &mut ModelContext<Self>) {
1216 let buffer = self.buffer.read(cx);
1217 let prev_len = self.edit_steps.len();
1218 self.edit_steps.retain(|step| {
1219 step.source_range.start.is_valid(buffer) && step.source_range.end.is_valid(buffer)
1220 });
1221 if self.edit_steps.len() != prev_len {
1222 cx.emit(ContextEvent::EditStepsChanged);
1223 cx.notify();
1224 }
1225 }
1226
1227 fn parse_edit_steps_in_range(&mut self, range: Range<usize>, cx: &mut ModelContext<Self>) {
1228 let mut new_edit_steps = Vec::new();
1229
1230 self.buffer.update(cx, |buffer, _cx| {
1231 let mut message_lines = buffer.as_rope().chunks_in_range(range).lines();
1232 let mut in_step = false;
1233 let mut step_start = 0;
1234 let mut line_start_offset = message_lines.offset();
1235
1236 while let Some(line) = message_lines.next() {
1237 if let Some(step_start_index) = line.find("<step>") {
1238 if !in_step {
1239 in_step = true;
1240 step_start = line_start_offset + step_start_index;
1241 }
1242 }
1243
1244 if let Some(step_end_index) = line.find("</step>") {
1245 if in_step {
1246 let start_anchor = buffer.anchor_after(step_start);
1247 let end_anchor = buffer
1248 .anchor_before(line_start_offset + step_end_index + "</step>".len());
1249 let source_range = start_anchor..end_anchor;
1250
1251 // Check if a step with the same range already exists
1252 let existing_step_index = self.edit_steps.binary_search_by(|probe| {
1253 probe.source_range.cmp(&source_range, buffer)
1254 });
1255
1256 if let Err(ix) = existing_step_index {
1257 // Step doesn't exist, so add it
1258 new_edit_steps.push((
1259 ix,
1260 EditStep {
1261 source_range,
1262 operations: None,
1263 },
1264 ));
1265 }
1266
1267 in_step = false;
1268 }
1269 }
1270
1271 line_start_offset = message_lines.offset();
1272 }
1273 });
1274
1275 // Insert new steps and generate their corresponding tasks
1276 for (index, mut step) in new_edit_steps.into_iter().rev() {
1277 let task = self.generate_edit_step_operations(&step, cx);
1278 step.operations = Some(EditStepOperations::Pending(task));
1279 self.edit_steps.insert(index, step);
1280 }
1281
1282 cx.emit(ContextEvent::EditStepsChanged);
1283 cx.notify();
1284 }
1285
1286 fn generate_edit_step_operations(
1287 &self,
1288 edit_step: &EditStep,
1289 cx: &mut ModelContext<Self>,
1290 ) -> Task<Result<()>> {
1291 let mut request = self.to_completion_request(cx);
1292 let edit_step_range = edit_step.source_range.clone();
1293 let step_text = self
1294 .buffer
1295 .read(cx)
1296 .text_for_range(edit_step_range.clone())
1297 .collect::<String>();
1298
1299 cx.spawn(|this, mut cx| async move {
1300 let prompt_store = cx.update(|cx| PromptStore::global(cx))?.await?;
1301
1302 let mut prompt = prompt_store.operations_prompt();
1303 prompt.push_str(&step_text);
1304
1305 request.messages.push(LanguageModelRequestMessage {
1306 role: Role::User,
1307 content: prompt,
1308 });
1309
1310 let raw_output = cx
1311 .update(|cx| CompletionProvider::global(cx).complete(request, cx))?
1312 .await?;
1313
1314 let operations = Self::parse_edit_operations(&raw_output);
1315 this.update(&mut cx, |this, cx| {
1316 let step_index = this
1317 .edit_steps
1318 .binary_search_by(|step| {
1319 step.source_range
1320 .cmp(&edit_step_range, this.buffer.read(cx))
1321 })
1322 .map_err(|_| anyhow!("edit step not found"))?;
1323 if let Some(edit_step) = this.edit_steps.get_mut(step_index) {
1324 edit_step.operations = Some(EditStepOperations::Parsed {
1325 operations,
1326 raw_output,
1327 });
1328 cx.emit(ContextEvent::EditStepsChanged);
1329 }
1330 anyhow::Ok(())
1331 })?
1332 })
1333 }
1334
1335 fn parse_edit_operations(xml: &str) -> Vec<EditOperation> {
1336 let Some(start_ix) = xml.find("<operations>") else {
1337 return Vec::new();
1338 };
1339 let Some(end_ix) = xml[start_ix..].find("</operations>") else {
1340 return Vec::new();
1341 };
1342 let end_ix = end_ix + start_ix + "</operations>".len();
1343
1344 let doc = roxmltree::Document::parse(&xml[start_ix..end_ix]).log_err();
1345 doc.map_or(Vec::new(), |doc| {
1346 doc.root_element()
1347 .children()
1348 .map(|node| {
1349 let tag_name = node.tag_name().name();
1350 let path = node
1351 .attribute("path")
1352 .with_context(|| {
1353 format!("invalid node {node:?}, missing attribute 'path'")
1354 })?
1355 .to_string();
1356 let kind = match tag_name {
1357 "update" => EditOperationKind::Update {
1358 symbol: node
1359 .attribute("symbol")
1360 .with_context(|| {
1361 format!("invalid node {node:?}, missing attribute 'symbol'")
1362 })?
1363 .to_string(),
1364 description: node
1365 .attribute("description")
1366 .with_context(|| {
1367 format!(
1368 "invalid node {node:?}, missing attribute 'description'"
1369 )
1370 })?
1371 .to_string(),
1372 },
1373 "create" => EditOperationKind::Create {
1374 description: node
1375 .attribute("description")
1376 .with_context(|| {
1377 format!(
1378 "invalid node {node:?}, missing attribute 'description'"
1379 )
1380 })?
1381 .to_string(),
1382 },
1383 "insert_sibling_after" => EditOperationKind::InsertSiblingAfter {
1384 symbol: node
1385 .attribute("symbol")
1386 .with_context(|| {
1387 format!("invalid node {node:?}, missing attribute 'symbol'")
1388 })?
1389 .to_string(),
1390 description: node
1391 .attribute("description")
1392 .with_context(|| {
1393 format!(
1394 "invalid node {node:?}, missing attribute 'description'"
1395 )
1396 })?
1397 .to_string(),
1398 },
1399 "insert_sibling_before" => EditOperationKind::InsertSiblingBefore {
1400 symbol: node
1401 .attribute("symbol")
1402 .with_context(|| {
1403 format!("invalid node {node:?}, missing attribute 'symbol'")
1404 })?
1405 .to_string(),
1406 description: node
1407 .attribute("description")
1408 .with_context(|| {
1409 format!(
1410 "invalid node {node:?}, missing attribute 'description'"
1411 )
1412 })?
1413 .to_string(),
1414 },
1415 "prepend_child" => EditOperationKind::PrependChild {
1416 symbol: node.attribute("symbol").map(String::from),
1417 description: node
1418 .attribute("description")
1419 .with_context(|| {
1420 format!(
1421 "invalid node {node:?}, missing attribute 'description'"
1422 )
1423 })?
1424 .to_string(),
1425 },
1426 "append_child" => EditOperationKind::AppendChild {
1427 symbol: node.attribute("symbol").map(String::from),
1428 description: node
1429 .attribute("description")
1430 .with_context(|| {
1431 format!(
1432 "invalid node {node:?}, missing attribute 'description'"
1433 )
1434 })?
1435 .to_string(),
1436 },
1437 "delete" => EditOperationKind::Delete {
1438 symbol: node
1439 .attribute("symbol")
1440 .with_context(|| {
1441 format!("invalid node {node:?}, missing attribute 'symbol'")
1442 })?
1443 .to_string(),
1444 },
1445 _ => return Err(anyhow!("invalid node {node:?}")),
1446 };
1447 anyhow::Ok(EditOperation { path, kind })
1448 })
1449 .filter_map(|op| op.log_err())
1450 .collect()
1451 })
1452 }
1453
1454 pub fn pending_command_for_position(
1455 &mut self,
1456 position: language::Anchor,
1457 cx: &mut ModelContext<Self>,
1458 ) -> Option<&mut PendingSlashCommand> {
1459 let buffer = self.buffer.read(cx);
1460 match self
1461 .pending_slash_commands
1462 .binary_search_by(|probe| probe.source_range.end.cmp(&position, buffer))
1463 {
1464 Ok(ix) => Some(&mut self.pending_slash_commands[ix]),
1465 Err(ix) => {
1466 let cmd = self.pending_slash_commands.get_mut(ix)?;
1467 if position.cmp(&cmd.source_range.start, buffer).is_ge()
1468 && position.cmp(&cmd.source_range.end, buffer).is_le()
1469 {
1470 Some(cmd)
1471 } else {
1472 None
1473 }
1474 }
1475 }
1476 }
1477
1478 pub fn pending_commands_for_range(
1479 &self,
1480 range: Range<language::Anchor>,
1481 cx: &AppContext,
1482 ) -> &[PendingSlashCommand] {
1483 let range = self.pending_command_indices_for_range(range, cx);
1484 &self.pending_slash_commands[range]
1485 }
1486
1487 fn pending_command_indices_for_range(
1488 &self,
1489 range: Range<language::Anchor>,
1490 cx: &AppContext,
1491 ) -> Range<usize> {
1492 let buffer = self.buffer.read(cx);
1493 let start_ix = match self
1494 .pending_slash_commands
1495 .binary_search_by(|probe| probe.source_range.end.cmp(&range.start, &buffer))
1496 {
1497 Ok(ix) | Err(ix) => ix,
1498 };
1499 let end_ix = match self
1500 .pending_slash_commands
1501 .binary_search_by(|probe| probe.source_range.start.cmp(&range.end, &buffer))
1502 {
1503 Ok(ix) => ix + 1,
1504 Err(ix) => ix,
1505 };
1506 start_ix..end_ix
1507 }
1508
1509 pub fn insert_command_output(
1510 &mut self,
1511 command_range: Range<language::Anchor>,
1512 output: Task<Result<SlashCommandOutput>>,
1513 insert_trailing_newline: bool,
1514 cx: &mut ModelContext<Self>,
1515 ) {
1516 self.reparse_slash_commands(cx);
1517
1518 let insert_output_task = cx.spawn(|this, mut cx| {
1519 let command_range = command_range.clone();
1520 async move {
1521 let output = output.await;
1522 this.update(&mut cx, |this, cx| match output {
1523 Ok(mut output) => {
1524 if insert_trailing_newline {
1525 output.text.push('\n');
1526 }
1527
1528 let version = this.version.clone();
1529 let command_id = SlashCommandId(this.next_timestamp());
1530 let (operation, event) = this.buffer.update(cx, |buffer, cx| {
1531 let start = command_range.start.to_offset(buffer);
1532 let old_end = command_range.end.to_offset(buffer);
1533 let new_end = start + output.text.len();
1534 buffer.edit([(start..old_end, output.text)], None, cx);
1535
1536 let mut sections = output
1537 .sections
1538 .into_iter()
1539 .map(|section| SlashCommandOutputSection {
1540 range: buffer.anchor_after(start + section.range.start)
1541 ..buffer.anchor_before(start + section.range.end),
1542 icon: section.icon,
1543 label: section.label,
1544 })
1545 .collect::<Vec<_>>();
1546 sections.sort_by(|a, b| a.range.cmp(&b.range, buffer));
1547
1548 this.slash_command_output_sections
1549 .extend(sections.iter().cloned());
1550 this.slash_command_output_sections
1551 .sort_by(|a, b| a.range.cmp(&b.range, buffer));
1552
1553 let output_range =
1554 buffer.anchor_after(start)..buffer.anchor_before(new_end);
1555 this.finished_slash_commands.insert(command_id);
1556
1557 (
1558 ContextOperation::SlashCommandFinished {
1559 id: command_id,
1560 output_range: output_range.clone(),
1561 sections: sections.clone(),
1562 version,
1563 },
1564 ContextEvent::SlashCommandFinished {
1565 output_range,
1566 sections,
1567 run_commands_in_output: output.run_commands_in_text,
1568 },
1569 )
1570 });
1571
1572 this.push_op(operation, cx);
1573 cx.emit(event);
1574 }
1575 Err(error) => {
1576 if let Some(pending_command) =
1577 this.pending_command_for_position(command_range.start, cx)
1578 {
1579 pending_command.status =
1580 PendingSlashCommandStatus::Error(error.to_string());
1581 cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1582 removed: vec![pending_command.source_range.clone()],
1583 updated: vec![pending_command.clone()],
1584 });
1585 }
1586 }
1587 })
1588 .ok();
1589 }
1590 });
1591
1592 if let Some(pending_command) = self.pending_command_for_position(command_range.start, cx) {
1593 pending_command.status = PendingSlashCommandStatus::Running {
1594 _task: insert_output_task.shared(),
1595 };
1596 cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1597 removed: vec![pending_command.source_range.clone()],
1598 updated: vec![pending_command.clone()],
1599 });
1600 }
1601 }
1602
1603 pub fn completion_provider_changed(&mut self, cx: &mut ModelContext<Self>) {
1604 self.count_remaining_tokens(cx);
1605 }
1606
1607 pub fn assist(&mut self, cx: &mut ModelContext<Self>) -> Option<MessageAnchor> {
1608 let last_message_id = self.message_anchors.iter().rev().find_map(|message| {
1609 message
1610 .start
1611 .is_valid(self.buffer.read(cx))
1612 .then_some(message.id)
1613 })?;
1614
1615 if !CompletionProvider::global(cx).is_authenticated() {
1616 log::info!("completion provider has no credentials");
1617 return None;
1618 }
1619
1620 let request = self.to_completion_request(cx);
1621 let stream = CompletionProvider::global(cx).stream_completion(request, cx);
1622 let assistant_message = self
1623 .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1624 .unwrap();
1625
1626 // Queue up the user's next reply.
1627 let user_message = self
1628 .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
1629 .unwrap();
1630
1631 let task = cx.spawn({
1632 |this, mut cx| async move {
1633 let assistant_message_id = assistant_message.id;
1634 let mut response_latency = None;
1635 let stream_completion = async {
1636 let request_start = Instant::now();
1637 let mut chunks = stream.await?;
1638
1639 while let Some(chunk) = chunks.next().await {
1640 if response_latency.is_none() {
1641 response_latency = Some(request_start.elapsed());
1642 }
1643 let chunk = chunk?;
1644
1645 this.update(&mut cx, |this, cx| {
1646 let message_ix = this
1647 .message_anchors
1648 .iter()
1649 .position(|message| message.id == assistant_message_id)?;
1650 let message_range = this.buffer.update(cx, |buffer, cx| {
1651 let message_start_offset =
1652 this.message_anchors[message_ix].start.to_offset(buffer);
1653 let message_old_end_offset = this.message_anchors[message_ix + 1..]
1654 .iter()
1655 .find(|message| message.start.is_valid(buffer))
1656 .map_or(buffer.len(), |message| {
1657 message.start.to_offset(buffer).saturating_sub(1)
1658 });
1659 let message_new_end_offset = message_old_end_offset + chunk.len();
1660 buffer.edit(
1661 [(message_old_end_offset..message_old_end_offset, chunk)],
1662 None,
1663 cx,
1664 );
1665 message_start_offset..message_new_end_offset
1666 });
1667 this.parse_edit_steps_in_range(message_range, cx);
1668 cx.emit(ContextEvent::StreamedCompletion);
1669
1670 Some(())
1671 })?;
1672 smol::future::yield_now().await;
1673 }
1674
1675 this.update(&mut cx, |this, cx| {
1676 this.pending_completions
1677 .retain(|completion| completion.id != this.completion_count);
1678 this.summarize(false, cx);
1679 })?;
1680
1681 anyhow::Ok(())
1682 };
1683
1684 let result = stream_completion.await;
1685
1686 this.update(&mut cx, |this, cx| {
1687 let error_message = result
1688 .err()
1689 .map(|error| error.to_string().trim().to_string());
1690
1691 this.update_metadata(assistant_message_id, cx, |metadata| {
1692 if let Some(error_message) = error_message.as_ref() {
1693 metadata.status =
1694 MessageStatus::Error(SharedString::from(error_message.clone()));
1695 } else {
1696 metadata.status = MessageStatus::Done;
1697 }
1698 });
1699
1700 if let Some(telemetry) = this.telemetry.as_ref() {
1701 let model = CompletionProvider::global(cx).model();
1702 telemetry.report_assistant_event(
1703 Some(this.id.0.clone()),
1704 AssistantKind::Panel,
1705 model.telemetry_id(),
1706 response_latency,
1707 error_message,
1708 );
1709 }
1710 })
1711 .ok();
1712 }
1713 });
1714
1715 self.pending_completions.push(PendingCompletion {
1716 id: post_inc(&mut self.completion_count),
1717 _task: task,
1718 });
1719
1720 Some(user_message)
1721 }
1722
1723 pub fn to_completion_request(&self, cx: &AppContext) -> LanguageModelRequest {
1724 let messages = self
1725 .messages(cx)
1726 .filter(|message| matches!(message.status, MessageStatus::Done))
1727 .map(|message| message.to_request_message(self.buffer.read(cx)));
1728
1729 LanguageModelRequest {
1730 model: CompletionProvider::global(cx).model(),
1731 messages: messages.collect(),
1732 stop: vec![],
1733 temperature: 1.0,
1734 }
1735 }
1736
1737 pub fn cancel_last_assist(&mut self) -> bool {
1738 self.pending_completions.pop().is_some()
1739 }
1740
1741 pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
1742 for id in ids {
1743 if let Some(metadata) = self.messages_metadata.get(&id) {
1744 let role = metadata.role.cycle();
1745 self.update_metadata(id, cx, |metadata| metadata.role = role);
1746 }
1747 }
1748 }
1749
1750 pub fn update_metadata(
1751 &mut self,
1752 id: MessageId,
1753 cx: &mut ModelContext<Self>,
1754 f: impl FnOnce(&mut MessageMetadata),
1755 ) {
1756 let version = self.version.clone();
1757 let timestamp = self.next_timestamp();
1758 if let Some(metadata) = self.messages_metadata.get_mut(&id) {
1759 f(metadata);
1760 metadata.timestamp = timestamp;
1761 let operation = ContextOperation::UpdateMessage {
1762 message_id: id,
1763 metadata: metadata.clone(),
1764 version,
1765 };
1766 self.push_op(operation, cx);
1767 cx.emit(ContextEvent::MessagesEdited);
1768 cx.notify();
1769 }
1770 }
1771
1772 fn insert_message_after(
1773 &mut self,
1774 message_id: MessageId,
1775 role: Role,
1776 status: MessageStatus,
1777 cx: &mut ModelContext<Self>,
1778 ) -> Option<MessageAnchor> {
1779 if let Some(prev_message_ix) = self
1780 .message_anchors
1781 .iter()
1782 .position(|message| message.id == message_id)
1783 {
1784 // Find the next valid message after the one we were given.
1785 let mut next_message_ix = prev_message_ix + 1;
1786 while let Some(next_message) = self.message_anchors.get(next_message_ix) {
1787 if next_message.start.is_valid(self.buffer.read(cx)) {
1788 break;
1789 }
1790 next_message_ix += 1;
1791 }
1792
1793 let start = self.buffer.update(cx, |buffer, cx| {
1794 let offset = self
1795 .message_anchors
1796 .get(next_message_ix)
1797 .map_or(buffer.len(), |message| {
1798 buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
1799 });
1800 buffer.edit([(offset..offset, "\n")], None, cx);
1801 buffer.anchor_before(offset + 1)
1802 });
1803
1804 let version = self.version.clone();
1805 let anchor = MessageAnchor {
1806 id: MessageId(self.next_timestamp()),
1807 start,
1808 };
1809 let metadata = MessageMetadata {
1810 role,
1811 status,
1812 timestamp: anchor.id.0,
1813 };
1814 self.insert_message(anchor.clone(), metadata.clone(), cx);
1815 self.push_op(
1816 ContextOperation::InsertMessage {
1817 anchor: anchor.clone(),
1818 metadata,
1819 version,
1820 },
1821 cx,
1822 );
1823 Some(anchor)
1824 } else {
1825 None
1826 }
1827 }
1828
1829 pub fn split_message(
1830 &mut self,
1831 range: Range<usize>,
1832 cx: &mut ModelContext<Self>,
1833 ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
1834 let start_message = self.message_for_offset(range.start, cx);
1835 let end_message = self.message_for_offset(range.end, cx);
1836 if let Some((start_message, end_message)) = start_message.zip(end_message) {
1837 // Prevent splitting when range spans multiple messages.
1838 if start_message.id != end_message.id {
1839 return (None, None);
1840 }
1841
1842 let message = start_message;
1843 let role = message.role;
1844 let mut edited_buffer = false;
1845
1846 let mut suffix_start = None;
1847 if range.start > message.offset_range.start && range.end < message.offset_range.end - 1
1848 {
1849 if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
1850 suffix_start = Some(range.end + 1);
1851 } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
1852 suffix_start = Some(range.end);
1853 }
1854 }
1855
1856 let version = self.version.clone();
1857 let suffix = if let Some(suffix_start) = suffix_start {
1858 MessageAnchor {
1859 id: MessageId(self.next_timestamp()),
1860 start: self.buffer.read(cx).anchor_before(suffix_start),
1861 }
1862 } else {
1863 self.buffer.update(cx, |buffer, cx| {
1864 buffer.edit([(range.end..range.end, "\n")], None, cx);
1865 });
1866 edited_buffer = true;
1867 MessageAnchor {
1868 id: MessageId(self.next_timestamp()),
1869 start: self.buffer.read(cx).anchor_before(range.end + 1),
1870 }
1871 };
1872
1873 let suffix_metadata = MessageMetadata {
1874 role,
1875 status: MessageStatus::Done,
1876 timestamp: suffix.id.0,
1877 };
1878 self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
1879 self.push_op(
1880 ContextOperation::InsertMessage {
1881 anchor: suffix.clone(),
1882 metadata: suffix_metadata,
1883 version,
1884 },
1885 cx,
1886 );
1887
1888 let new_messages =
1889 if range.start == range.end || range.start == message.offset_range.start {
1890 (None, Some(suffix))
1891 } else {
1892 let mut prefix_end = None;
1893 if range.start > message.offset_range.start
1894 && range.end < message.offset_range.end - 1
1895 {
1896 if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
1897 prefix_end = Some(range.start + 1);
1898 } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
1899 == Some('\n')
1900 {
1901 prefix_end = Some(range.start);
1902 }
1903 }
1904
1905 let version = self.version.clone();
1906 let selection = if let Some(prefix_end) = prefix_end {
1907 MessageAnchor {
1908 id: MessageId(self.next_timestamp()),
1909 start: self.buffer.read(cx).anchor_before(prefix_end),
1910 }
1911 } else {
1912 self.buffer.update(cx, |buffer, cx| {
1913 buffer.edit([(range.start..range.start, "\n")], None, cx)
1914 });
1915 edited_buffer = true;
1916 MessageAnchor {
1917 id: MessageId(self.next_timestamp()),
1918 start: self.buffer.read(cx).anchor_before(range.end + 1),
1919 }
1920 };
1921
1922 let selection_metadata = MessageMetadata {
1923 role,
1924 status: MessageStatus::Done,
1925 timestamp: selection.id.0,
1926 };
1927 self.insert_message(selection.clone(), selection_metadata.clone(), cx);
1928 self.push_op(
1929 ContextOperation::InsertMessage {
1930 anchor: selection.clone(),
1931 metadata: selection_metadata,
1932 version,
1933 },
1934 cx,
1935 );
1936
1937 (Some(selection), Some(suffix))
1938 };
1939
1940 if !edited_buffer {
1941 cx.emit(ContextEvent::MessagesEdited);
1942 }
1943 new_messages
1944 } else {
1945 (None, None)
1946 }
1947 }
1948
1949 fn insert_message(
1950 &mut self,
1951 new_anchor: MessageAnchor,
1952 new_metadata: MessageMetadata,
1953 cx: &mut ModelContext<Self>,
1954 ) {
1955 cx.emit(ContextEvent::MessagesEdited);
1956
1957 self.messages_metadata.insert(new_anchor.id, new_metadata);
1958
1959 let buffer = self.buffer.read(cx);
1960 let insertion_ix = self
1961 .message_anchors
1962 .iter()
1963 .position(|anchor| {
1964 let comparison = new_anchor.start.cmp(&anchor.start, buffer);
1965 comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
1966 })
1967 .unwrap_or(self.message_anchors.len());
1968 self.message_anchors.insert(insertion_ix, new_anchor);
1969 }
1970
1971 pub(super) fn summarize(&mut self, replace_old: bool, cx: &mut ModelContext<Self>) {
1972 if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
1973 if !CompletionProvider::global(cx).is_authenticated() {
1974 return;
1975 }
1976
1977 let messages = self
1978 .messages(cx)
1979 .map(|message| message.to_request_message(self.buffer.read(cx)))
1980 .chain(Some(LanguageModelRequestMessage {
1981 role: Role::User,
1982 content: "Summarize the context into a short title without punctuation.".into(),
1983 }));
1984 let request = LanguageModelRequest {
1985 model: CompletionProvider::global(cx).model(),
1986 messages: messages.collect(),
1987 stop: vec![],
1988 temperature: 1.0,
1989 };
1990
1991 let stream = CompletionProvider::global(cx).stream_completion(request, cx);
1992 self.pending_summary = cx.spawn(|this, mut cx| {
1993 async move {
1994 let mut messages = stream.await?;
1995
1996 let mut replaced = !replace_old;
1997 while let Some(message) = messages.next().await {
1998 let text = message?;
1999 let mut lines = text.lines();
2000 this.update(&mut cx, |this, cx| {
2001 let version = this.version.clone();
2002 let timestamp = this.next_timestamp();
2003 let summary = this.summary.get_or_insert(ContextSummary::default());
2004 if !replaced && replace_old {
2005 summary.text.clear();
2006 replaced = true;
2007 }
2008 summary.text.extend(lines.next());
2009 summary.timestamp = timestamp;
2010 let operation = ContextOperation::UpdateSummary {
2011 summary: summary.clone(),
2012 version,
2013 };
2014 this.push_op(operation, cx);
2015 cx.emit(ContextEvent::SummaryChanged);
2016 })?;
2017
2018 // Stop if the LLM generated multiple lines.
2019 if lines.next().is_some() {
2020 break;
2021 }
2022 }
2023
2024 this.update(&mut cx, |this, cx| {
2025 let version = this.version.clone();
2026 let timestamp = this.next_timestamp();
2027 if let Some(summary) = this.summary.as_mut() {
2028 summary.done = true;
2029 summary.timestamp = timestamp;
2030 let operation = ContextOperation::UpdateSummary {
2031 summary: summary.clone(),
2032 version,
2033 };
2034 this.push_op(operation, cx);
2035 cx.emit(ContextEvent::SummaryChanged);
2036 }
2037 })?;
2038
2039 anyhow::Ok(())
2040 }
2041 .log_err()
2042 });
2043 }
2044 }
2045
2046 fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
2047 self.messages_for_offsets([offset], cx).pop()
2048 }
2049
2050 pub fn messages_for_offsets(
2051 &self,
2052 offsets: impl IntoIterator<Item = usize>,
2053 cx: &AppContext,
2054 ) -> Vec<Message> {
2055 let mut result = Vec::new();
2056
2057 let mut messages = self.messages(cx).peekable();
2058 let mut offsets = offsets.into_iter().peekable();
2059 let mut current_message = messages.next();
2060 while let Some(offset) = offsets.next() {
2061 // Locate the message that contains the offset.
2062 while current_message.as_ref().map_or(false, |message| {
2063 !message.offset_range.contains(&offset) && messages.peek().is_some()
2064 }) {
2065 current_message = messages.next();
2066 }
2067 let Some(message) = current_message.as_ref() else {
2068 break;
2069 };
2070
2071 // Skip offsets that are in the same message.
2072 while offsets.peek().map_or(false, |offset| {
2073 message.offset_range.contains(offset) || messages.peek().is_none()
2074 }) {
2075 offsets.next();
2076 }
2077
2078 result.push(message.clone());
2079 }
2080 result
2081 }
2082
2083 pub fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
2084 let buffer = self.buffer.read(cx);
2085 let mut message_anchors = self.message_anchors.iter().enumerate().peekable();
2086 iter::from_fn(move || {
2087 if let Some((start_ix, message_anchor)) = message_anchors.next() {
2088 let metadata = self.messages_metadata.get(&message_anchor.id)?;
2089 let message_start = message_anchor.start.to_offset(buffer);
2090 let mut message_end = None;
2091 let mut end_ix = start_ix;
2092 while let Some((_, next_message)) = message_anchors.peek() {
2093 if next_message.start.is_valid(buffer) {
2094 message_end = Some(next_message.start);
2095 break;
2096 } else {
2097 end_ix += 1;
2098 message_anchors.next();
2099 }
2100 }
2101 let message_end = message_end
2102 .unwrap_or(language::Anchor::MAX)
2103 .to_offset(buffer);
2104
2105 return Some(Message {
2106 index_range: start_ix..end_ix,
2107 offset_range: message_start..message_end,
2108 id: message_anchor.id,
2109 anchor: message_anchor.start,
2110 role: metadata.role,
2111 status: metadata.status.clone(),
2112 });
2113 }
2114 None
2115 })
2116 }
2117
2118 pub fn save(
2119 &mut self,
2120 debounce: Option<Duration>,
2121 fs: Arc<dyn Fs>,
2122 cx: &mut ModelContext<Context>,
2123 ) {
2124 if self.replica_id() != ReplicaId::default() {
2125 // Prevent saving a remote context for now.
2126 return;
2127 }
2128
2129 self.pending_save = cx.spawn(|this, mut cx| async move {
2130 if let Some(debounce) = debounce {
2131 cx.background_executor().timer(debounce).await;
2132 }
2133
2134 let (old_path, summary) = this.read_with(&cx, |this, _| {
2135 let path = this.path.clone();
2136 let summary = if let Some(summary) = this.summary.as_ref() {
2137 if summary.done {
2138 Some(summary.text.clone())
2139 } else {
2140 None
2141 }
2142 } else {
2143 None
2144 };
2145 (path, summary)
2146 })?;
2147
2148 if let Some(summary) = summary {
2149 let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2150 let mut discriminant = 1;
2151 let mut new_path;
2152 loop {
2153 new_path = contexts_dir().join(&format!(
2154 "{} - {}.zed.json",
2155 summary.trim(),
2156 discriminant
2157 ));
2158 if fs.is_file(&new_path).await {
2159 discriminant += 1;
2160 } else {
2161 break;
2162 }
2163 }
2164
2165 fs.create_dir(contexts_dir().as_ref()).await?;
2166 fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
2167 .await?;
2168 if let Some(old_path) = old_path {
2169 if new_path != old_path {
2170 fs.remove_file(
2171 &old_path,
2172 RemoveOptions {
2173 recursive: false,
2174 ignore_if_not_exists: true,
2175 },
2176 )
2177 .await?;
2178 }
2179 }
2180
2181 this.update(&mut cx, |this, _| this.path = Some(new_path))?;
2182 }
2183
2184 Ok(())
2185 });
2186 }
2187
2188 pub(crate) fn custom_summary(&mut self, custom_summary: String, cx: &mut ModelContext<Self>) {
2189 let timestamp = self.next_timestamp();
2190 let summary = self.summary.get_or_insert(ContextSummary::default());
2191 summary.timestamp = timestamp;
2192 summary.done = true;
2193 summary.text = custom_summary;
2194 cx.emit(ContextEvent::SummaryChanged);
2195 }
2196}
2197
2198#[derive(Debug, Default)]
2199pub struct ContextVersion {
2200 context: clock::Global,
2201 buffer: clock::Global,
2202}
2203
2204impl ContextVersion {
2205 pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2206 Self {
2207 context: language::proto::deserialize_version(&proto.context_version),
2208 buffer: language::proto::deserialize_version(&proto.buffer_version),
2209 }
2210 }
2211
2212 pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
2213 proto::ContextVersion {
2214 context_id: context_id.to_proto(),
2215 context_version: language::proto::serialize_version(&self.context),
2216 buffer_version: language::proto::serialize_version(&self.buffer),
2217 }
2218 }
2219}
2220
2221#[derive(Clone)]
2222pub struct PendingSlashCommand {
2223 pub name: String,
2224 pub argument: Option<String>,
2225 pub status: PendingSlashCommandStatus,
2226 pub source_range: Range<language::Anchor>,
2227}
2228
2229#[derive(Clone)]
2230pub enum PendingSlashCommandStatus {
2231 Idle,
2232 Running { _task: Shared<Task<()>> },
2233 Error(String),
2234}
2235
2236#[derive(Serialize, Deserialize)]
2237pub struct SavedMessage {
2238 pub id: MessageId,
2239 pub start: usize,
2240 pub metadata: MessageMetadata,
2241}
2242
2243#[derive(Serialize, Deserialize)]
2244pub struct SavedContext {
2245 pub id: Option<ContextId>,
2246 pub zed: String,
2247 pub version: String,
2248 pub text: String,
2249 pub messages: Vec<SavedMessage>,
2250 pub summary: String,
2251 pub slash_command_output_sections:
2252 Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2253}
2254
2255impl SavedContext {
2256 pub const VERSION: &'static str = "0.4.0";
2257
2258 pub fn from_json(json: &str) -> Result<Self> {
2259 let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
2260 match saved_context_json
2261 .get("version")
2262 .ok_or_else(|| anyhow!("version not found"))?
2263 {
2264 serde_json::Value::String(version) => match version.as_str() {
2265 SavedContext::VERSION => {
2266 Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
2267 }
2268 SavedContextV0_3_0::VERSION => {
2269 let saved_context =
2270 serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
2271 Ok(saved_context.upgrade())
2272 }
2273 SavedContextV0_2_0::VERSION => {
2274 let saved_context =
2275 serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
2276 Ok(saved_context.upgrade())
2277 }
2278 SavedContextV0_1_0::VERSION => {
2279 let saved_context =
2280 serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
2281 Ok(saved_context.upgrade())
2282 }
2283 _ => Err(anyhow!("unrecognized saved context version: {}", version)),
2284 },
2285 _ => Err(anyhow!("version not found on saved context")),
2286 }
2287 }
2288
2289 fn into_ops(
2290 self,
2291 buffer: &Model<Buffer>,
2292 cx: &mut ModelContext<Context>,
2293 ) -> Vec<ContextOperation> {
2294 let mut operations = Vec::new();
2295 let mut version = clock::Global::new();
2296 let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
2297
2298 let mut first_message_metadata = None;
2299 for message in self.messages {
2300 if message.id == MessageId(clock::Lamport::default()) {
2301 first_message_metadata = Some(message.metadata);
2302 } else {
2303 operations.push(ContextOperation::InsertMessage {
2304 anchor: MessageAnchor {
2305 id: message.id,
2306 start: buffer.read(cx).anchor_before(message.start),
2307 },
2308 metadata: MessageMetadata {
2309 role: message.metadata.role,
2310 status: message.metadata.status,
2311 timestamp: message.metadata.timestamp,
2312 },
2313 version: version.clone(),
2314 });
2315 version.observe(message.id.0);
2316 next_timestamp.observe(message.id.0);
2317 }
2318 }
2319
2320 if let Some(metadata) = first_message_metadata {
2321 let timestamp = next_timestamp.tick();
2322 operations.push(ContextOperation::UpdateMessage {
2323 message_id: MessageId(clock::Lamport::default()),
2324 metadata: MessageMetadata {
2325 role: metadata.role,
2326 status: metadata.status,
2327 timestamp,
2328 },
2329 version: version.clone(),
2330 });
2331 version.observe(timestamp);
2332 }
2333
2334 let timestamp = next_timestamp.tick();
2335 operations.push(ContextOperation::SlashCommandFinished {
2336 id: SlashCommandId(timestamp),
2337 output_range: language::Anchor::MIN..language::Anchor::MAX,
2338 sections: self
2339 .slash_command_output_sections
2340 .into_iter()
2341 .map(|section| {
2342 let buffer = buffer.read(cx);
2343 SlashCommandOutputSection {
2344 range: buffer.anchor_after(section.range.start)
2345 ..buffer.anchor_before(section.range.end),
2346 icon: section.icon,
2347 label: section.label,
2348 }
2349 })
2350 .collect(),
2351 version: version.clone(),
2352 });
2353 version.observe(timestamp);
2354
2355 let timestamp = next_timestamp.tick();
2356 operations.push(ContextOperation::UpdateSummary {
2357 summary: ContextSummary {
2358 text: self.summary,
2359 done: true,
2360 timestamp,
2361 },
2362 version: version.clone(),
2363 });
2364 version.observe(timestamp);
2365
2366 operations
2367 }
2368}
2369
2370#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
2371struct SavedMessageIdPreV0_4_0(usize);
2372
2373#[derive(Serialize, Deserialize)]
2374struct SavedMessagePreV0_4_0 {
2375 id: SavedMessageIdPreV0_4_0,
2376 start: usize,
2377}
2378
2379#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2380struct SavedMessageMetadataPreV0_4_0 {
2381 role: Role,
2382 status: MessageStatus,
2383}
2384
2385#[derive(Serialize, Deserialize)]
2386struct SavedContextV0_3_0 {
2387 id: Option<ContextId>,
2388 zed: String,
2389 version: String,
2390 text: String,
2391 messages: Vec<SavedMessagePreV0_4_0>,
2392 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2393 summary: String,
2394 slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2395}
2396
2397impl SavedContextV0_3_0 {
2398 const VERSION: &'static str = "0.3.0";
2399
2400 fn upgrade(self) -> SavedContext {
2401 SavedContext {
2402 id: self.id,
2403 zed: self.zed,
2404 version: SavedContext::VERSION.into(),
2405 text: self.text,
2406 messages: self
2407 .messages
2408 .into_iter()
2409 .filter_map(|message| {
2410 let metadata = self.message_metadata.get(&message.id)?;
2411 let timestamp = clock::Lamport {
2412 replica_id: ReplicaId::default(),
2413 value: message.id.0 as u32,
2414 };
2415 Some(SavedMessage {
2416 id: MessageId(timestamp),
2417 start: message.start,
2418 metadata: MessageMetadata {
2419 role: metadata.role,
2420 status: metadata.status.clone(),
2421 timestamp,
2422 },
2423 })
2424 })
2425 .collect(),
2426 summary: self.summary,
2427 slash_command_output_sections: self.slash_command_output_sections,
2428 }
2429 }
2430}
2431
2432#[derive(Serialize, Deserialize)]
2433struct SavedContextV0_2_0 {
2434 id: Option<ContextId>,
2435 zed: String,
2436 version: String,
2437 text: String,
2438 messages: Vec<SavedMessagePreV0_4_0>,
2439 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2440 summary: String,
2441}
2442
2443impl SavedContextV0_2_0 {
2444 const VERSION: &'static str = "0.2.0";
2445
2446 fn upgrade(self) -> SavedContext {
2447 SavedContextV0_3_0 {
2448 id: self.id,
2449 zed: self.zed,
2450 version: SavedContextV0_3_0::VERSION.to_string(),
2451 text: self.text,
2452 messages: self.messages,
2453 message_metadata: self.message_metadata,
2454 summary: self.summary,
2455 slash_command_output_sections: Vec::new(),
2456 }
2457 .upgrade()
2458 }
2459}
2460
2461#[derive(Serialize, Deserialize)]
2462struct SavedContextV0_1_0 {
2463 id: Option<ContextId>,
2464 zed: String,
2465 version: String,
2466 text: String,
2467 messages: Vec<SavedMessagePreV0_4_0>,
2468 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2469 summary: String,
2470 api_url: Option<String>,
2471 model: OpenAiModel,
2472}
2473
2474impl SavedContextV0_1_0 {
2475 const VERSION: &'static str = "0.1.0";
2476
2477 fn upgrade(self) -> SavedContext {
2478 SavedContextV0_2_0 {
2479 id: self.id,
2480 zed: self.zed,
2481 version: SavedContextV0_2_0::VERSION.to_string(),
2482 text: self.text,
2483 messages: self.messages,
2484 message_metadata: self.message_metadata,
2485 summary: self.summary,
2486 }
2487 .upgrade()
2488 }
2489}
2490
2491#[derive(Clone)]
2492pub struct SavedContextMetadata {
2493 pub title: String,
2494 pub path: PathBuf,
2495 pub mtime: chrono::DateTime<chrono::Local>,
2496}
2497
2498#[cfg(test)]
2499mod tests {
2500 use super::*;
2501 use crate::{
2502 assistant_panel, prompt_library,
2503 slash_command::{active_command, file_command},
2504 MessageId,
2505 };
2506 use assistant_slash_command::{ArgumentCompletion, SlashCommand};
2507 use completion::FakeCompletionProvider;
2508 use fs::FakeFs;
2509 use gpui::{AppContext, TestAppContext, WeakView};
2510 use indoc::indoc;
2511 use language::LspAdapterDelegate;
2512 use parking_lot::Mutex;
2513 use project::Project;
2514 use rand::prelude::*;
2515 use serde_json::json;
2516 use settings::SettingsStore;
2517 use std::{cell::RefCell, env, rc::Rc, sync::atomic::AtomicBool};
2518 use text::{network::Network, ToPoint};
2519 use ui::WindowContext;
2520 use unindent::Unindent;
2521 use util::{test::marked_text_ranges, RandomCharIter};
2522 use workspace::Workspace;
2523
2524 #[gpui::test]
2525 fn test_inserting_and_removing_messages(cx: &mut AppContext) {
2526 let settings_store = SettingsStore::test(cx);
2527 FakeCompletionProvider::setup_test(cx);
2528 cx.set_global(settings_store);
2529 assistant_panel::init(cx);
2530 let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2531
2532 let context = cx.new_model(|cx| Context::local(registry, None, cx));
2533 let buffer = context.read(cx).buffer.clone();
2534
2535 let message_1 = context.read(cx).message_anchors[0].clone();
2536 assert_eq!(
2537 messages(&context, cx),
2538 vec![(message_1.id, Role::User, 0..0)]
2539 );
2540
2541 let message_2 = context.update(cx, |context, cx| {
2542 context
2543 .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx)
2544 .unwrap()
2545 });
2546 assert_eq!(
2547 messages(&context, cx),
2548 vec![
2549 (message_1.id, Role::User, 0..1),
2550 (message_2.id, Role::Assistant, 1..1)
2551 ]
2552 );
2553
2554 buffer.update(cx, |buffer, cx| {
2555 buffer.edit([(0..0, "1"), (1..1, "2")], None, cx)
2556 });
2557 assert_eq!(
2558 messages(&context, cx),
2559 vec![
2560 (message_1.id, Role::User, 0..2),
2561 (message_2.id, Role::Assistant, 2..3)
2562 ]
2563 );
2564
2565 let message_3 = context.update(cx, |context, cx| {
2566 context
2567 .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2568 .unwrap()
2569 });
2570 assert_eq!(
2571 messages(&context, cx),
2572 vec![
2573 (message_1.id, Role::User, 0..2),
2574 (message_2.id, Role::Assistant, 2..4),
2575 (message_3.id, Role::User, 4..4)
2576 ]
2577 );
2578
2579 let message_4 = context.update(cx, |context, cx| {
2580 context
2581 .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2582 .unwrap()
2583 });
2584 assert_eq!(
2585 messages(&context, cx),
2586 vec![
2587 (message_1.id, Role::User, 0..2),
2588 (message_2.id, Role::Assistant, 2..4),
2589 (message_4.id, Role::User, 4..5),
2590 (message_3.id, Role::User, 5..5),
2591 ]
2592 );
2593
2594 buffer.update(cx, |buffer, cx| {
2595 buffer.edit([(4..4, "C"), (5..5, "D")], None, cx)
2596 });
2597 assert_eq!(
2598 messages(&context, cx),
2599 vec![
2600 (message_1.id, Role::User, 0..2),
2601 (message_2.id, Role::Assistant, 2..4),
2602 (message_4.id, Role::User, 4..6),
2603 (message_3.id, Role::User, 6..7),
2604 ]
2605 );
2606
2607 // Deleting across message boundaries merges the messages.
2608 buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx));
2609 assert_eq!(
2610 messages(&context, cx),
2611 vec![
2612 (message_1.id, Role::User, 0..3),
2613 (message_3.id, Role::User, 3..4),
2614 ]
2615 );
2616
2617 // Undoing the deletion should also undo the merge.
2618 buffer.update(cx, |buffer, cx| buffer.undo(cx));
2619 assert_eq!(
2620 messages(&context, cx),
2621 vec![
2622 (message_1.id, Role::User, 0..2),
2623 (message_2.id, Role::Assistant, 2..4),
2624 (message_4.id, Role::User, 4..6),
2625 (message_3.id, Role::User, 6..7),
2626 ]
2627 );
2628
2629 // Redoing the deletion should also redo the merge.
2630 buffer.update(cx, |buffer, cx| buffer.redo(cx));
2631 assert_eq!(
2632 messages(&context, cx),
2633 vec![
2634 (message_1.id, Role::User, 0..3),
2635 (message_3.id, Role::User, 3..4),
2636 ]
2637 );
2638
2639 // Ensure we can still insert after a merged message.
2640 let message_5 = context.update(cx, |context, cx| {
2641 context
2642 .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
2643 .unwrap()
2644 });
2645 assert_eq!(
2646 messages(&context, cx),
2647 vec![
2648 (message_1.id, Role::User, 0..3),
2649 (message_5.id, Role::System, 3..4),
2650 (message_3.id, Role::User, 4..5)
2651 ]
2652 );
2653 }
2654
2655 #[gpui::test]
2656 fn test_message_splitting(cx: &mut AppContext) {
2657 let settings_store = SettingsStore::test(cx);
2658 cx.set_global(settings_store);
2659 FakeCompletionProvider::setup_test(cx);
2660 assistant_panel::init(cx);
2661 let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2662
2663 let context = cx.new_model(|cx| Context::local(registry, None, cx));
2664 let buffer = context.read(cx).buffer.clone();
2665
2666 let message_1 = context.read(cx).message_anchors[0].clone();
2667 assert_eq!(
2668 messages(&context, cx),
2669 vec![(message_1.id, Role::User, 0..0)]
2670 );
2671
2672 buffer.update(cx, |buffer, cx| {
2673 buffer.edit([(0..0, "aaa\nbbb\nccc\nddd\n")], None, cx)
2674 });
2675
2676 let (_, message_2) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2677 let message_2 = message_2.unwrap();
2678
2679 // We recycle newlines in the middle of a split message
2680 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n");
2681 assert_eq!(
2682 messages(&context, cx),
2683 vec![
2684 (message_1.id, Role::User, 0..4),
2685 (message_2.id, Role::User, 4..16),
2686 ]
2687 );
2688
2689 let (_, message_3) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2690 let message_3 = message_3.unwrap();
2691
2692 // We don't recycle newlines at the end of a split message
2693 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2694 assert_eq!(
2695 messages(&context, cx),
2696 vec![
2697 (message_1.id, Role::User, 0..4),
2698 (message_3.id, Role::User, 4..5),
2699 (message_2.id, Role::User, 5..17),
2700 ]
2701 );
2702
2703 let (_, message_4) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2704 let message_4 = message_4.unwrap();
2705 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2706 assert_eq!(
2707 messages(&context, cx),
2708 vec![
2709 (message_1.id, Role::User, 0..4),
2710 (message_3.id, Role::User, 4..5),
2711 (message_2.id, Role::User, 5..9),
2712 (message_4.id, Role::User, 9..17),
2713 ]
2714 );
2715
2716 let (_, message_5) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2717 let message_5 = message_5.unwrap();
2718 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n");
2719 assert_eq!(
2720 messages(&context, cx),
2721 vec![
2722 (message_1.id, Role::User, 0..4),
2723 (message_3.id, Role::User, 4..5),
2724 (message_2.id, Role::User, 5..9),
2725 (message_4.id, Role::User, 9..10),
2726 (message_5.id, Role::User, 10..18),
2727 ]
2728 );
2729
2730 let (message_6, message_7) =
2731 context.update(cx, |context, cx| context.split_message(14..16, cx));
2732 let message_6 = message_6.unwrap();
2733 let message_7 = message_7.unwrap();
2734 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n");
2735 assert_eq!(
2736 messages(&context, cx),
2737 vec![
2738 (message_1.id, Role::User, 0..4),
2739 (message_3.id, Role::User, 4..5),
2740 (message_2.id, Role::User, 5..9),
2741 (message_4.id, Role::User, 9..10),
2742 (message_5.id, Role::User, 10..14),
2743 (message_6.id, Role::User, 14..17),
2744 (message_7.id, Role::User, 17..19),
2745 ]
2746 );
2747 }
2748
2749 #[gpui::test]
2750 fn test_messages_for_offsets(cx: &mut AppContext) {
2751 let settings_store = SettingsStore::test(cx);
2752 FakeCompletionProvider::setup_test(cx);
2753 cx.set_global(settings_store);
2754 assistant_panel::init(cx);
2755 let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2756 let context = cx.new_model(|cx| Context::local(registry, None, cx));
2757 let buffer = context.read(cx).buffer.clone();
2758
2759 let message_1 = context.read(cx).message_anchors[0].clone();
2760 assert_eq!(
2761 messages(&context, cx),
2762 vec![(message_1.id, Role::User, 0..0)]
2763 );
2764
2765 buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx));
2766 let message_2 = context
2767 .update(cx, |context, cx| {
2768 context.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx)
2769 })
2770 .unwrap();
2771 buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx));
2772
2773 let message_3 = context
2774 .update(cx, |context, cx| {
2775 context.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2776 })
2777 .unwrap();
2778 buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx));
2779
2780 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc");
2781 assert_eq!(
2782 messages(&context, cx),
2783 vec![
2784 (message_1.id, Role::User, 0..4),
2785 (message_2.id, Role::User, 4..8),
2786 (message_3.id, Role::User, 8..11)
2787 ]
2788 );
2789
2790 assert_eq!(
2791 message_ids_for_offsets(&context, &[0, 4, 9], cx),
2792 [message_1.id, message_2.id, message_3.id]
2793 );
2794 assert_eq!(
2795 message_ids_for_offsets(&context, &[0, 1, 11], cx),
2796 [message_1.id, message_3.id]
2797 );
2798
2799 let message_4 = context
2800 .update(cx, |context, cx| {
2801 context.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx)
2802 })
2803 .unwrap();
2804 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n");
2805 assert_eq!(
2806 messages(&context, cx),
2807 vec![
2808 (message_1.id, Role::User, 0..4),
2809 (message_2.id, Role::User, 4..8),
2810 (message_3.id, Role::User, 8..12),
2811 (message_4.id, Role::User, 12..12)
2812 ]
2813 );
2814 assert_eq!(
2815 message_ids_for_offsets(&context, &[0, 4, 8, 12], cx),
2816 [message_1.id, message_2.id, message_3.id, message_4.id]
2817 );
2818
2819 fn message_ids_for_offsets(
2820 context: &Model<Context>,
2821 offsets: &[usize],
2822 cx: &AppContext,
2823 ) -> Vec<MessageId> {
2824 context
2825 .read(cx)
2826 .messages_for_offsets(offsets.iter().copied(), cx)
2827 .into_iter()
2828 .map(|message| message.id)
2829 .collect()
2830 }
2831 }
2832
2833 #[gpui::test]
2834 async fn test_slash_commands(cx: &mut TestAppContext) {
2835 let settings_store = cx.update(SettingsStore::test);
2836 cx.set_global(settings_store);
2837 cx.update(FakeCompletionProvider::setup_test);
2838 cx.update(Project::init_settings);
2839 cx.update(assistant_panel::init);
2840 let fs = FakeFs::new(cx.background_executor.clone());
2841
2842 fs.insert_tree(
2843 "/test",
2844 json!({
2845 "src": {
2846 "lib.rs": "fn one() -> usize { 1 }",
2847 "main.rs": "
2848 use crate::one;
2849 fn main() { one(); }
2850 ".unindent(),
2851 }
2852 }),
2853 )
2854 .await;
2855
2856 let slash_command_registry = cx.update(SlashCommandRegistry::default_global);
2857 slash_command_registry.register_command(file_command::FileSlashCommand, false);
2858 slash_command_registry.register_command(active_command::ActiveSlashCommand, false);
2859
2860 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
2861 let context = cx.new_model(|cx| Context::local(registry.clone(), None, cx));
2862
2863 let output_ranges = Rc::new(RefCell::new(HashSet::default()));
2864 context.update(cx, |_, cx| {
2865 cx.subscribe(&context, {
2866 let ranges = output_ranges.clone();
2867 move |_, _, event, _| match event {
2868 ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
2869 for range in removed {
2870 ranges.borrow_mut().remove(range);
2871 }
2872 for command in updated {
2873 ranges.borrow_mut().insert(command.source_range.clone());
2874 }
2875 }
2876 _ => {}
2877 }
2878 })
2879 .detach();
2880 });
2881
2882 let buffer = context.read_with(cx, |context, _| context.buffer.clone());
2883
2884 // Insert a slash command
2885 buffer.update(cx, |buffer, cx| {
2886 buffer.edit([(0..0, "/file src/lib.rs")], None, cx);
2887 });
2888 assert_text_and_output_ranges(
2889 &buffer,
2890 &output_ranges.borrow(),
2891 "
2892 «/file src/lib.rs»
2893 "
2894 .unindent()
2895 .trim_end(),
2896 cx,
2897 );
2898
2899 // Edit the argument of the slash command.
2900 buffer.update(cx, |buffer, cx| {
2901 let edit_offset = buffer.text().find("lib.rs").unwrap();
2902 buffer.edit([(edit_offset..edit_offset + "lib".len(), "main")], None, cx);
2903 });
2904 assert_text_and_output_ranges(
2905 &buffer,
2906 &output_ranges.borrow(),
2907 "
2908 «/file src/main.rs»
2909 "
2910 .unindent()
2911 .trim_end(),
2912 cx,
2913 );
2914
2915 // Edit the name of the slash command, using one that doesn't exist.
2916 buffer.update(cx, |buffer, cx| {
2917 let edit_offset = buffer.text().find("/file").unwrap();
2918 buffer.edit(
2919 [(edit_offset..edit_offset + "/file".len(), "/unknown")],
2920 None,
2921 cx,
2922 );
2923 });
2924 assert_text_and_output_ranges(
2925 &buffer,
2926 &output_ranges.borrow(),
2927 "
2928 /unknown src/main.rs
2929 "
2930 .unindent()
2931 .trim_end(),
2932 cx,
2933 );
2934
2935 #[track_caller]
2936 fn assert_text_and_output_ranges(
2937 buffer: &Model<Buffer>,
2938 ranges: &HashSet<Range<language::Anchor>>,
2939 expected_marked_text: &str,
2940 cx: &mut TestAppContext,
2941 ) {
2942 let (expected_text, expected_ranges) = marked_text_ranges(expected_marked_text, false);
2943 let (actual_text, actual_ranges) = buffer.update(cx, |buffer, _| {
2944 let mut ranges = ranges
2945 .iter()
2946 .map(|range| range.to_offset(buffer))
2947 .collect::<Vec<_>>();
2948 ranges.sort_by_key(|a| a.start);
2949 (buffer.text(), ranges)
2950 });
2951
2952 assert_eq!(actual_text, expected_text);
2953 assert_eq!(actual_ranges, expected_ranges);
2954 }
2955 }
2956
2957 #[gpui::test]
2958 async fn test_edit_step_parsing(cx: &mut TestAppContext) {
2959 cx.update(prompt_library::init);
2960 let settings_store = cx.update(SettingsStore::test);
2961 cx.set_global(settings_store);
2962 let fake_provider = cx.update(FakeCompletionProvider::setup_test);
2963 cx.update(assistant_panel::init);
2964 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
2965
2966 // Create a new context
2967 let context = cx.new_model(|cx| Context::local(registry.clone(), None, cx));
2968 let buffer = context.read_with(cx, |context, _| context.buffer.clone());
2969
2970 // Simulate user input
2971 let user_message = indoc! {r#"
2972 Please refactor this code:
2973
2974 fn main() {
2975 println!("Hello, World!");
2976 }
2977 "#};
2978 buffer.update(cx, |buffer, cx| {
2979 buffer.edit([(0..0, user_message)], None, cx);
2980 });
2981
2982 // Simulate LLM response with edit steps
2983 let llm_response = indoc! {r#"
2984 Sure, I can help you refactor that code. Here's a step-by-step process:
2985
2986 <step>
2987 First, let's extract the greeting into a separate function:
2988
2989 ```rust
2990 fn greet() {
2991 println!("Hello, World!");
2992 }
2993
2994 fn main() {
2995 greet();
2996 }
2997 ```
2998 </step>
2999
3000 <step>
3001 Now, let's make the greeting customizable:
3002
3003 ```rust
3004 fn greet(name: &str) {
3005 println!("Hello, {}!", name);
3006 }
3007
3008 fn main() {
3009 greet("World");
3010 }
3011 ```
3012 </step>
3013
3014 These changes make the code more modular and flexible.
3015 "#};
3016
3017 // Simulate the assist method to trigger the LLM response
3018 context.update(cx, |context, cx| context.assist(cx));
3019 cx.run_until_parked();
3020
3021 // Retrieve the assistant response message's start from the context
3022 let response_start_row = context.read_with(cx, |context, cx| {
3023 let buffer = context.buffer.read(cx);
3024 context.message_anchors[1].start.to_point(buffer).row
3025 });
3026
3027 // Simulate the LLM completion
3028 fake_provider.send_last_completion_chunk(llm_response.to_string());
3029 fake_provider.finish_last_completion();
3030
3031 // Wait for the completion to be processed
3032 cx.run_until_parked();
3033
3034 // Verify that the edit steps were parsed correctly
3035 context.read_with(cx, |context, cx| {
3036 assert_eq!(
3037 edit_steps(context, cx),
3038 vec![
3039 Point::new(response_start_row + 2, 0)..Point::new(response_start_row + 14, 7),
3040 Point::new(response_start_row + 16, 0)..Point::new(response_start_row + 28, 7),
3041 ]
3042 );
3043 });
3044
3045 fn edit_steps(context: &Context, cx: &AppContext) -> Vec<Range<Point>> {
3046 context
3047 .edit_steps
3048 .iter()
3049 .map(|step| {
3050 let buffer = context.buffer.read(cx);
3051 step.source_range.to_point(buffer)
3052 })
3053 .collect()
3054 }
3055 }
3056
3057 #[test]
3058 fn test_parse_edit_operations() {
3059 let operations = indoc! {r#"
3060 Here are the operations to make all fields of the Canvas struct private:
3061
3062 <operations>
3063 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub pixels" description="Remove pub keyword from pixels field" />
3064 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub size" description="Remove pub keyword from size field" />
3065 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub stride" description="Remove pub keyword from stride field" />
3066 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub format" description="Remove pub keyword from format field" />
3067 </operations>
3068 "#};
3069
3070 let parsed_operations = Context::parse_edit_operations(operations);
3071 assert_eq!(
3072 parsed_operations,
3073 vec![
3074 EditOperation {
3075 path: "font-kit/src/canvas.rs".to_string(),
3076 kind: EditOperationKind::Update {
3077 symbol: "pub struct Canvas pub pixels".to_string(),
3078 description: "Remove pub keyword from pixels field".to_string(),
3079 },
3080 },
3081 EditOperation {
3082 path: "font-kit/src/canvas.rs".to_string(),
3083 kind: EditOperationKind::Update {
3084 symbol: "pub struct Canvas pub size".to_string(),
3085 description: "Remove pub keyword from size field".to_string(),
3086 },
3087 },
3088 EditOperation {
3089 path: "font-kit/src/canvas.rs".to_string(),
3090 kind: EditOperationKind::Update {
3091 symbol: "pub struct Canvas pub stride".to_string(),
3092 description: "Remove pub keyword from stride 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 format".to_string(),
3099 description: "Remove pub keyword from format field".to_string(),
3100 },
3101 },
3102 ]
3103 );
3104 }
3105
3106 #[gpui::test]
3107 async fn test_serialization(cx: &mut TestAppContext) {
3108 let settings_store = cx.update(SettingsStore::test);
3109 cx.set_global(settings_store);
3110 cx.update(FakeCompletionProvider::setup_test);
3111 cx.update(assistant_panel::init);
3112 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3113 let context = cx.new_model(|cx| Context::local(registry.clone(), None, cx));
3114 let buffer = context.read_with(cx, |context, _| context.buffer.clone());
3115 let message_0 = context.read_with(cx, |context, _| context.message_anchors[0].id);
3116 let message_1 = context.update(cx, |context, cx| {
3117 context
3118 .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx)
3119 .unwrap()
3120 });
3121 let message_2 = context.update(cx, |context, cx| {
3122 context
3123 .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3124 .unwrap()
3125 });
3126 buffer.update(cx, |buffer, cx| {
3127 buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx);
3128 buffer.finalize_last_transaction();
3129 });
3130 let _message_3 = context.update(cx, |context, cx| {
3131 context
3132 .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx)
3133 .unwrap()
3134 });
3135 buffer.update(cx, |buffer, cx| buffer.undo(cx));
3136 assert_eq!(buffer.read_with(cx, |buffer, _| buffer.text()), "a\nb\nc\n");
3137 assert_eq!(
3138 cx.read(|cx| messages(&context, cx)),
3139 [
3140 (message_0, Role::User, 0..2),
3141 (message_1.id, Role::Assistant, 2..6),
3142 (message_2.id, Role::System, 6..6),
3143 ]
3144 );
3145
3146 let serialized_context = context.read_with(cx, |context, cx| context.serialize(cx));
3147 let deserialized_context = cx.new_model(|cx| {
3148 Context::deserialize(
3149 serialized_context,
3150 Default::default(),
3151 registry.clone(),
3152 None,
3153 cx,
3154 )
3155 });
3156 let deserialized_buffer =
3157 deserialized_context.read_with(cx, |context, _| context.buffer.clone());
3158 assert_eq!(
3159 deserialized_buffer.read_with(cx, |buffer, _| buffer.text()),
3160 "a\nb\nc\n"
3161 );
3162 assert_eq!(
3163 cx.read(|cx| messages(&deserialized_context, cx)),
3164 [
3165 (message_0, Role::User, 0..2),
3166 (message_1.id, Role::Assistant, 2..6),
3167 (message_2.id, Role::System, 6..6),
3168 ]
3169 );
3170 }
3171
3172 #[gpui::test(iterations = 100)]
3173 async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: StdRng) {
3174 let min_peers = env::var("MIN_PEERS")
3175 .map(|i| i.parse().expect("invalid `MIN_PEERS` variable"))
3176 .unwrap_or(2);
3177 let max_peers = env::var("MAX_PEERS")
3178 .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
3179 .unwrap_or(5);
3180 let operations = env::var("OPERATIONS")
3181 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3182 .unwrap_or(50);
3183
3184 let settings_store = cx.update(SettingsStore::test);
3185 cx.set_global(settings_store);
3186 cx.update(FakeCompletionProvider::setup_test);
3187 cx.update(assistant_panel::init);
3188 let slash_commands = cx.update(SlashCommandRegistry::default_global);
3189 slash_commands.register_command(FakeSlashCommand("cmd-1".into()), false);
3190 slash_commands.register_command(FakeSlashCommand("cmd-2".into()), false);
3191 slash_commands.register_command(FakeSlashCommand("cmd-3".into()), false);
3192
3193 let registry = Arc::new(LanguageRegistry::test(cx.background_executor.clone()));
3194 let network = Arc::new(Mutex::new(Network::new(rng.clone())));
3195 let mut contexts = Vec::new();
3196
3197 let num_peers = rng.gen_range(min_peers..=max_peers);
3198 let context_id = ContextId::new();
3199 for i in 0..num_peers {
3200 let context = cx.new_model(|cx| {
3201 Context::new(
3202 context_id.clone(),
3203 i as ReplicaId,
3204 language::Capability::ReadWrite,
3205 registry.clone(),
3206 None,
3207 cx,
3208 )
3209 });
3210
3211 cx.update(|cx| {
3212 cx.subscribe(&context, {
3213 let network = network.clone();
3214 move |_, event, _| {
3215 if let ContextEvent::Operation(op) = event {
3216 network
3217 .lock()
3218 .broadcast(i as ReplicaId, vec![op.to_proto()]);
3219 }
3220 }
3221 })
3222 .detach();
3223 });
3224
3225 contexts.push(context);
3226 network.lock().add_peer(i as ReplicaId);
3227 }
3228
3229 let mut mutation_count = operations;
3230
3231 while mutation_count > 0
3232 || !network.lock().is_idle()
3233 || network.lock().contains_disconnected_peers()
3234 {
3235 let context_index = rng.gen_range(0..contexts.len());
3236 let context = &contexts[context_index];
3237
3238 match rng.gen_range(0..100) {
3239 0..=29 if mutation_count > 0 => {
3240 log::info!("Context {}: edit buffer", context_index);
3241 context.update(cx, |context, cx| {
3242 context
3243 .buffer
3244 .update(cx, |buffer, cx| buffer.randomly_edit(&mut rng, 1, cx));
3245 });
3246 mutation_count -= 1;
3247 }
3248 30..=44 if mutation_count > 0 => {
3249 context.update(cx, |context, cx| {
3250 let range = context.buffer.read(cx).random_byte_range(0, &mut rng);
3251 log::info!("Context {}: split message at {:?}", context_index, range);
3252 context.split_message(range, cx);
3253 });
3254 mutation_count -= 1;
3255 }
3256 45..=59 if mutation_count > 0 => {
3257 context.update(cx, |context, cx| {
3258 if let Some(message) = context.messages(cx).choose(&mut rng) {
3259 let role = *[Role::User, Role::Assistant, Role::System]
3260 .choose(&mut rng)
3261 .unwrap();
3262 log::info!(
3263 "Context {}: insert message after {:?} with {:?}",
3264 context_index,
3265 message.id,
3266 role
3267 );
3268 context.insert_message_after(message.id, role, MessageStatus::Done, cx);
3269 }
3270 });
3271 mutation_count -= 1;
3272 }
3273 60..=74 if mutation_count > 0 => {
3274 context.update(cx, |context, cx| {
3275 let command_text = "/".to_string()
3276 + slash_commands
3277 .command_names()
3278 .choose(&mut rng)
3279 .unwrap()
3280 .clone()
3281 .as_ref();
3282
3283 let command_range = context.buffer.update(cx, |buffer, cx| {
3284 let offset = buffer.random_byte_range(0, &mut rng).start;
3285 buffer.edit(
3286 [(offset..offset, format!("\n{}\n", command_text))],
3287 None,
3288 cx,
3289 );
3290 offset + 1..offset + 1 + command_text.len()
3291 });
3292
3293 let output_len = rng.gen_range(1..=10);
3294 let output_text = RandomCharIter::new(&mut rng)
3295 .filter(|c| *c != '\r')
3296 .take(output_len)
3297 .collect::<String>();
3298
3299 let num_sections = rng.gen_range(0..=3);
3300 let mut sections = Vec::with_capacity(num_sections);
3301 for _ in 0..num_sections {
3302 let section_start = rng.gen_range(0..output_len);
3303 let section_end = rng.gen_range(section_start..=output_len);
3304 sections.push(SlashCommandOutputSection {
3305 range: section_start..section_end,
3306 icon: ui::IconName::Ai,
3307 label: "section".into(),
3308 });
3309 }
3310
3311 log::info!(
3312 "Context {}: insert slash command output at {:?} with {:?}",
3313 context_index,
3314 command_range,
3315 sections
3316 );
3317
3318 let command_range =
3319 context.buffer.read(cx).anchor_after(command_range.start)
3320 ..context.buffer.read(cx).anchor_after(command_range.end);
3321 context.insert_command_output(
3322 command_range,
3323 Task::ready(Ok(SlashCommandOutput {
3324 text: output_text,
3325 sections,
3326 run_commands_in_text: false,
3327 })),
3328 true,
3329 cx,
3330 );
3331 });
3332 cx.run_until_parked();
3333 mutation_count -= 1;
3334 }
3335 75..=84 if mutation_count > 0 => {
3336 context.update(cx, |context, cx| {
3337 if let Some(message) = context.messages(cx).choose(&mut rng) {
3338 let new_status = match rng.gen_range(0..3) {
3339 0 => MessageStatus::Done,
3340 1 => MessageStatus::Pending,
3341 _ => MessageStatus::Error(SharedString::from("Random error")),
3342 };
3343 log::info!(
3344 "Context {}: update message {:?} status to {:?}",
3345 context_index,
3346 message.id,
3347 new_status
3348 );
3349 context.update_metadata(message.id, cx, |metadata| {
3350 metadata.status = new_status;
3351 });
3352 }
3353 });
3354 mutation_count -= 1;
3355 }
3356 _ => {
3357 let replica_id = context_index as ReplicaId;
3358 if network.lock().is_disconnected(replica_id) {
3359 network.lock().reconnect_peer(replica_id, 0);
3360
3361 let (ops_to_send, ops_to_receive) = cx.read(|cx| {
3362 let host_context = &contexts[0].read(cx);
3363 let guest_context = context.read(cx);
3364 (
3365 guest_context.serialize_ops(&host_context.version(cx), cx),
3366 host_context.serialize_ops(&guest_context.version(cx), cx),
3367 )
3368 });
3369 let ops_to_send = ops_to_send.await;
3370 let ops_to_receive = ops_to_receive
3371 .await
3372 .into_iter()
3373 .map(ContextOperation::from_proto)
3374 .collect::<Result<Vec<_>>>()
3375 .unwrap();
3376 log::info!(
3377 "Context {}: reconnecting. Sent {} operations, received {} operations",
3378 context_index,
3379 ops_to_send.len(),
3380 ops_to_receive.len()
3381 );
3382
3383 network.lock().broadcast(replica_id, ops_to_send);
3384 context
3385 .update(cx, |context, cx| context.apply_ops(ops_to_receive, cx))
3386 .unwrap();
3387 } else if rng.gen_bool(0.1) && replica_id != 0 {
3388 log::info!("Context {}: disconnecting", context_index);
3389 network.lock().disconnect_peer(replica_id);
3390 } else if network.lock().has_unreceived(replica_id) {
3391 log::info!("Context {}: applying operations", context_index);
3392 let ops = network.lock().receive(replica_id);
3393 let ops = ops
3394 .into_iter()
3395 .map(ContextOperation::from_proto)
3396 .collect::<Result<Vec<_>>>()
3397 .unwrap();
3398 context
3399 .update(cx, |context, cx| context.apply_ops(ops, cx))
3400 .unwrap();
3401 }
3402 }
3403 }
3404 }
3405
3406 cx.read(|cx| {
3407 let first_context = contexts[0].read(cx);
3408 for context in &contexts[1..] {
3409 let context = context.read(cx);
3410 assert!(context.pending_ops.is_empty());
3411 assert_eq!(
3412 context.buffer.read(cx).text(),
3413 first_context.buffer.read(cx).text(),
3414 "Context {} text != Context 0 text",
3415 context.buffer.read(cx).replica_id()
3416 );
3417 assert_eq!(
3418 context.message_anchors,
3419 first_context.message_anchors,
3420 "Context {} messages != Context 0 messages",
3421 context.buffer.read(cx).replica_id()
3422 );
3423 assert_eq!(
3424 context.messages_metadata,
3425 first_context.messages_metadata,
3426 "Context {} message metadata != Context 0 message metadata",
3427 context.buffer.read(cx).replica_id()
3428 );
3429 assert_eq!(
3430 context.slash_command_output_sections,
3431 first_context.slash_command_output_sections,
3432 "Context {} slash command output sections != Context 0 slash command output sections",
3433 context.buffer.read(cx).replica_id()
3434 );
3435 }
3436 });
3437 }
3438
3439 fn messages(context: &Model<Context>, cx: &AppContext) -> Vec<(MessageId, Role, Range<usize>)> {
3440 context
3441 .read(cx)
3442 .messages(cx)
3443 .map(|message| (message.id, message.role, message.offset_range))
3444 .collect()
3445 }
3446
3447 #[derive(Clone)]
3448 struct FakeSlashCommand(String);
3449
3450 impl SlashCommand for FakeSlashCommand {
3451 fn name(&self) -> String {
3452 self.0.clone()
3453 }
3454
3455 fn description(&self) -> String {
3456 format!("Fake slash command: {}", self.0)
3457 }
3458
3459 fn menu_text(&self) -> String {
3460 format!("Run fake command: {}", self.0)
3461 }
3462
3463 fn complete_argument(
3464 self: Arc<Self>,
3465 _query: String,
3466 _cancel: Arc<AtomicBool>,
3467 _workspace: Option<WeakView<Workspace>>,
3468 _cx: &mut AppContext,
3469 ) -> Task<Result<Vec<ArgumentCompletion>>> {
3470 Task::ready(Ok(vec![]))
3471 }
3472
3473 fn requires_argument(&self) -> bool {
3474 false
3475 }
3476
3477 fn run(
3478 self: Arc<Self>,
3479 _argument: Option<&str>,
3480 _workspace: WeakView<Workspace>,
3481 _delegate: Arc<dyn LspAdapterDelegate>,
3482 _cx: &mut WindowContext,
3483 ) -> Task<Result<SlashCommandOutput>> {
3484 Task::ready(Ok(SlashCommandOutput {
3485 text: format!("Executed fake command: {}", self.0),
3486 sections: vec![],
3487 run_commands_in_text: false,
3488 }))
3489 }
3490 }
3491}