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;
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(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 fn summarize(&mut self, cx: &mut ModelContext<Self>) {
1972 if 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 while let Some(message) = messages.next().await {
1997 let text = message?;
1998 let mut lines = text.lines();
1999 this.update(&mut cx, |this, cx| {
2000 let version = this.version.clone();
2001 let timestamp = this.next_timestamp();
2002 let summary = this.summary.get_or_insert(Default::default());
2003 summary.text.extend(lines.next());
2004 summary.timestamp = timestamp;
2005 let operation = ContextOperation::UpdateSummary {
2006 summary: summary.clone(),
2007 version,
2008 };
2009 this.push_op(operation, cx);
2010 cx.emit(ContextEvent::SummaryChanged);
2011 })?;
2012
2013 // Stop if the LLM generated multiple lines.
2014 if lines.next().is_some() {
2015 break;
2016 }
2017 }
2018
2019 this.update(&mut cx, |this, cx| {
2020 let version = this.version.clone();
2021 let timestamp = this.next_timestamp();
2022 if let Some(summary) = this.summary.as_mut() {
2023 summary.done = true;
2024 summary.timestamp = timestamp;
2025 let operation = ContextOperation::UpdateSummary {
2026 summary: summary.clone(),
2027 version,
2028 };
2029 this.push_op(operation, cx);
2030 cx.emit(ContextEvent::SummaryChanged);
2031 }
2032 })?;
2033
2034 anyhow::Ok(())
2035 }
2036 .log_err()
2037 });
2038 }
2039 }
2040
2041 fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
2042 self.messages_for_offsets([offset], cx).pop()
2043 }
2044
2045 pub fn messages_for_offsets(
2046 &self,
2047 offsets: impl IntoIterator<Item = usize>,
2048 cx: &AppContext,
2049 ) -> Vec<Message> {
2050 let mut result = Vec::new();
2051
2052 let mut messages = self.messages(cx).peekable();
2053 let mut offsets = offsets.into_iter().peekable();
2054 let mut current_message = messages.next();
2055 while let Some(offset) = offsets.next() {
2056 // Locate the message that contains the offset.
2057 while current_message.as_ref().map_or(false, |message| {
2058 !message.offset_range.contains(&offset) && messages.peek().is_some()
2059 }) {
2060 current_message = messages.next();
2061 }
2062 let Some(message) = current_message.as_ref() else {
2063 break;
2064 };
2065
2066 // Skip offsets that are in the same message.
2067 while offsets.peek().map_or(false, |offset| {
2068 message.offset_range.contains(offset) || messages.peek().is_none()
2069 }) {
2070 offsets.next();
2071 }
2072
2073 result.push(message.clone());
2074 }
2075 result
2076 }
2077
2078 pub fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
2079 let buffer = self.buffer.read(cx);
2080 let mut message_anchors = self.message_anchors.iter().enumerate().peekable();
2081 iter::from_fn(move || {
2082 if let Some((start_ix, message_anchor)) = message_anchors.next() {
2083 let metadata = self.messages_metadata.get(&message_anchor.id)?;
2084 let message_start = message_anchor.start.to_offset(buffer);
2085 let mut message_end = None;
2086 let mut end_ix = start_ix;
2087 while let Some((_, next_message)) = message_anchors.peek() {
2088 if next_message.start.is_valid(buffer) {
2089 message_end = Some(next_message.start);
2090 break;
2091 } else {
2092 end_ix += 1;
2093 message_anchors.next();
2094 }
2095 }
2096 let message_end = message_end
2097 .unwrap_or(language::Anchor::MAX)
2098 .to_offset(buffer);
2099
2100 return Some(Message {
2101 index_range: start_ix..end_ix,
2102 offset_range: message_start..message_end,
2103 id: message_anchor.id,
2104 anchor: message_anchor.start,
2105 role: metadata.role,
2106 status: metadata.status.clone(),
2107 });
2108 }
2109 None
2110 })
2111 }
2112
2113 pub fn save(
2114 &mut self,
2115 debounce: Option<Duration>,
2116 fs: Arc<dyn Fs>,
2117 cx: &mut ModelContext<Context>,
2118 ) {
2119 if self.replica_id() != ReplicaId::default() {
2120 // Prevent saving a remote context for now.
2121 return;
2122 }
2123
2124 self.pending_save = cx.spawn(|this, mut cx| async move {
2125 if let Some(debounce) = debounce {
2126 cx.background_executor().timer(debounce).await;
2127 }
2128
2129 let (old_path, summary) = this.read_with(&cx, |this, _| {
2130 let path = this.path.clone();
2131 let summary = if let Some(summary) = this.summary.as_ref() {
2132 if summary.done {
2133 Some(summary.text.clone())
2134 } else {
2135 None
2136 }
2137 } else {
2138 None
2139 };
2140 (path, summary)
2141 })?;
2142
2143 if let Some(summary) = summary {
2144 let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2145 let path = if let Some(old_path) = old_path {
2146 old_path
2147 } else {
2148 let mut discriminant = 1;
2149 let mut new_path;
2150 loop {
2151 new_path = contexts_dir().join(&format!(
2152 "{} - {}.zed.json",
2153 summary.trim(),
2154 discriminant
2155 ));
2156 if fs.is_file(&new_path).await {
2157 discriminant += 1;
2158 } else {
2159 break;
2160 }
2161 }
2162 new_path
2163 };
2164
2165 fs.create_dir(contexts_dir().as_ref()).await?;
2166 fs.atomic_write(path.clone(), serde_json::to_string(&context).unwrap())
2167 .await?;
2168 this.update(&mut cx, |this, _| this.path = Some(path))?;
2169 }
2170
2171 Ok(())
2172 });
2173 }
2174}
2175
2176#[derive(Debug, Default)]
2177pub struct ContextVersion {
2178 context: clock::Global,
2179 buffer: clock::Global,
2180}
2181
2182impl ContextVersion {
2183 pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2184 Self {
2185 context: language::proto::deserialize_version(&proto.context_version),
2186 buffer: language::proto::deserialize_version(&proto.buffer_version),
2187 }
2188 }
2189
2190 pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
2191 proto::ContextVersion {
2192 context_id: context_id.to_proto(),
2193 context_version: language::proto::serialize_version(&self.context),
2194 buffer_version: language::proto::serialize_version(&self.buffer),
2195 }
2196 }
2197}
2198
2199#[derive(Clone)]
2200pub struct PendingSlashCommand {
2201 pub name: String,
2202 pub argument: Option<String>,
2203 pub status: PendingSlashCommandStatus,
2204 pub source_range: Range<language::Anchor>,
2205}
2206
2207#[derive(Clone)]
2208pub enum PendingSlashCommandStatus {
2209 Idle,
2210 Running { _task: Shared<Task<()>> },
2211 Error(String),
2212}
2213
2214#[derive(Serialize, Deserialize)]
2215pub struct SavedMessage {
2216 pub id: MessageId,
2217 pub start: usize,
2218 pub metadata: MessageMetadata,
2219}
2220
2221#[derive(Serialize, Deserialize)]
2222pub struct SavedContext {
2223 pub id: Option<ContextId>,
2224 pub zed: String,
2225 pub version: String,
2226 pub text: String,
2227 pub messages: Vec<SavedMessage>,
2228 pub summary: String,
2229 pub slash_command_output_sections:
2230 Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2231}
2232
2233impl SavedContext {
2234 pub const VERSION: &'static str = "0.4.0";
2235
2236 pub fn from_json(json: &str) -> Result<Self> {
2237 let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
2238 match saved_context_json
2239 .get("version")
2240 .ok_or_else(|| anyhow!("version not found"))?
2241 {
2242 serde_json::Value::String(version) => match version.as_str() {
2243 SavedContext::VERSION => {
2244 Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
2245 }
2246 SavedContextV0_3_0::VERSION => {
2247 let saved_context =
2248 serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
2249 Ok(saved_context.upgrade())
2250 }
2251 SavedContextV0_2_0::VERSION => {
2252 let saved_context =
2253 serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
2254 Ok(saved_context.upgrade())
2255 }
2256 SavedContextV0_1_0::VERSION => {
2257 let saved_context =
2258 serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
2259 Ok(saved_context.upgrade())
2260 }
2261 _ => Err(anyhow!("unrecognized saved context version: {}", version)),
2262 },
2263 _ => Err(anyhow!("version not found on saved context")),
2264 }
2265 }
2266
2267 fn into_ops(
2268 self,
2269 buffer: &Model<Buffer>,
2270 cx: &mut ModelContext<Context>,
2271 ) -> Vec<ContextOperation> {
2272 let mut operations = Vec::new();
2273 let mut version = clock::Global::new();
2274 let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
2275
2276 let mut first_message_metadata = None;
2277 for message in self.messages {
2278 if message.id == MessageId(clock::Lamport::default()) {
2279 first_message_metadata = Some(message.metadata);
2280 } else {
2281 operations.push(ContextOperation::InsertMessage {
2282 anchor: MessageAnchor {
2283 id: message.id,
2284 start: buffer.read(cx).anchor_before(message.start),
2285 },
2286 metadata: MessageMetadata {
2287 role: message.metadata.role,
2288 status: message.metadata.status,
2289 timestamp: message.metadata.timestamp,
2290 },
2291 version: version.clone(),
2292 });
2293 version.observe(message.id.0);
2294 next_timestamp.observe(message.id.0);
2295 }
2296 }
2297
2298 if let Some(metadata) = first_message_metadata {
2299 let timestamp = next_timestamp.tick();
2300 operations.push(ContextOperation::UpdateMessage {
2301 message_id: MessageId(clock::Lamport::default()),
2302 metadata: MessageMetadata {
2303 role: metadata.role,
2304 status: metadata.status,
2305 timestamp,
2306 },
2307 version: version.clone(),
2308 });
2309 version.observe(timestamp);
2310 }
2311
2312 let timestamp = next_timestamp.tick();
2313 operations.push(ContextOperation::SlashCommandFinished {
2314 id: SlashCommandId(timestamp),
2315 output_range: language::Anchor::MIN..language::Anchor::MAX,
2316 sections: self
2317 .slash_command_output_sections
2318 .into_iter()
2319 .map(|section| {
2320 let buffer = buffer.read(cx);
2321 SlashCommandOutputSection {
2322 range: buffer.anchor_after(section.range.start)
2323 ..buffer.anchor_before(section.range.end),
2324 icon: section.icon,
2325 label: section.label,
2326 }
2327 })
2328 .collect(),
2329 version: version.clone(),
2330 });
2331 version.observe(timestamp);
2332
2333 let timestamp = next_timestamp.tick();
2334 operations.push(ContextOperation::UpdateSummary {
2335 summary: ContextSummary {
2336 text: self.summary,
2337 done: true,
2338 timestamp,
2339 },
2340 version: version.clone(),
2341 });
2342 version.observe(timestamp);
2343
2344 operations
2345 }
2346}
2347
2348#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
2349struct SavedMessageIdPreV0_4_0(usize);
2350
2351#[derive(Serialize, Deserialize)]
2352struct SavedMessagePreV0_4_0 {
2353 id: SavedMessageIdPreV0_4_0,
2354 start: usize,
2355}
2356
2357#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2358struct SavedMessageMetadataPreV0_4_0 {
2359 role: Role,
2360 status: MessageStatus,
2361}
2362
2363#[derive(Serialize, Deserialize)]
2364struct SavedContextV0_3_0 {
2365 id: Option<ContextId>,
2366 zed: String,
2367 version: String,
2368 text: String,
2369 messages: Vec<SavedMessagePreV0_4_0>,
2370 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2371 summary: String,
2372 slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2373}
2374
2375impl SavedContextV0_3_0 {
2376 const VERSION: &'static str = "0.3.0";
2377
2378 fn upgrade(self) -> SavedContext {
2379 SavedContext {
2380 id: self.id,
2381 zed: self.zed,
2382 version: SavedContext::VERSION.into(),
2383 text: self.text,
2384 messages: self
2385 .messages
2386 .into_iter()
2387 .filter_map(|message| {
2388 let metadata = self.message_metadata.get(&message.id)?;
2389 let timestamp = clock::Lamport {
2390 replica_id: ReplicaId::default(),
2391 value: message.id.0 as u32,
2392 };
2393 Some(SavedMessage {
2394 id: MessageId(timestamp),
2395 start: message.start,
2396 metadata: MessageMetadata {
2397 role: metadata.role,
2398 status: metadata.status.clone(),
2399 timestamp,
2400 },
2401 })
2402 })
2403 .collect(),
2404 summary: self.summary,
2405 slash_command_output_sections: self.slash_command_output_sections,
2406 }
2407 }
2408}
2409
2410#[derive(Serialize, Deserialize)]
2411struct SavedContextV0_2_0 {
2412 id: Option<ContextId>,
2413 zed: String,
2414 version: String,
2415 text: String,
2416 messages: Vec<SavedMessagePreV0_4_0>,
2417 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2418 summary: String,
2419}
2420
2421impl SavedContextV0_2_0 {
2422 const VERSION: &'static str = "0.2.0";
2423
2424 fn upgrade(self) -> SavedContext {
2425 SavedContextV0_3_0 {
2426 id: self.id,
2427 zed: self.zed,
2428 version: SavedContextV0_3_0::VERSION.to_string(),
2429 text: self.text,
2430 messages: self.messages,
2431 message_metadata: self.message_metadata,
2432 summary: self.summary,
2433 slash_command_output_sections: Vec::new(),
2434 }
2435 .upgrade()
2436 }
2437}
2438
2439#[derive(Serialize, Deserialize)]
2440struct SavedContextV0_1_0 {
2441 id: Option<ContextId>,
2442 zed: String,
2443 version: String,
2444 text: String,
2445 messages: Vec<SavedMessagePreV0_4_0>,
2446 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2447 summary: String,
2448 api_url: Option<String>,
2449 model: OpenAiModel,
2450}
2451
2452impl SavedContextV0_1_0 {
2453 const VERSION: &'static str = "0.1.0";
2454
2455 fn upgrade(self) -> SavedContext {
2456 SavedContextV0_2_0 {
2457 id: self.id,
2458 zed: self.zed,
2459 version: SavedContextV0_2_0::VERSION.to_string(),
2460 text: self.text,
2461 messages: self.messages,
2462 message_metadata: self.message_metadata,
2463 summary: self.summary,
2464 }
2465 .upgrade()
2466 }
2467}
2468
2469#[derive(Clone)]
2470pub struct SavedContextMetadata {
2471 pub title: String,
2472 pub path: PathBuf,
2473 pub mtime: chrono::DateTime<chrono::Local>,
2474}
2475
2476#[cfg(test)]
2477mod tests {
2478 use super::*;
2479 use crate::{
2480 assistant_panel, prompt_library,
2481 slash_command::{active_command, file_command},
2482 MessageId,
2483 };
2484 use assistant_slash_command::{ArgumentCompletion, SlashCommand};
2485 use completion::FakeCompletionProvider;
2486 use fs::FakeFs;
2487 use gpui::{AppContext, TestAppContext, WeakView};
2488 use indoc::indoc;
2489 use language::LspAdapterDelegate;
2490 use parking_lot::Mutex;
2491 use project::Project;
2492 use rand::prelude::*;
2493 use serde_json::json;
2494 use settings::SettingsStore;
2495 use std::{cell::RefCell, env, rc::Rc, sync::atomic::AtomicBool};
2496 use text::{network::Network, ToPoint};
2497 use ui::WindowContext;
2498 use unindent::Unindent;
2499 use util::{test::marked_text_ranges, RandomCharIter};
2500 use workspace::Workspace;
2501
2502 #[gpui::test]
2503 fn test_inserting_and_removing_messages(cx: &mut AppContext) {
2504 let settings_store = SettingsStore::test(cx);
2505 FakeCompletionProvider::setup_test(cx);
2506 cx.set_global(settings_store);
2507 assistant_panel::init(cx);
2508 let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2509
2510 let context = cx.new_model(|cx| Context::local(registry, None, cx));
2511 let buffer = context.read(cx).buffer.clone();
2512
2513 let message_1 = context.read(cx).message_anchors[0].clone();
2514 assert_eq!(
2515 messages(&context, cx),
2516 vec![(message_1.id, Role::User, 0..0)]
2517 );
2518
2519 let message_2 = context.update(cx, |context, cx| {
2520 context
2521 .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx)
2522 .unwrap()
2523 });
2524 assert_eq!(
2525 messages(&context, cx),
2526 vec![
2527 (message_1.id, Role::User, 0..1),
2528 (message_2.id, Role::Assistant, 1..1)
2529 ]
2530 );
2531
2532 buffer.update(cx, |buffer, cx| {
2533 buffer.edit([(0..0, "1"), (1..1, "2")], None, cx)
2534 });
2535 assert_eq!(
2536 messages(&context, cx),
2537 vec![
2538 (message_1.id, Role::User, 0..2),
2539 (message_2.id, Role::Assistant, 2..3)
2540 ]
2541 );
2542
2543 let message_3 = context.update(cx, |context, cx| {
2544 context
2545 .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2546 .unwrap()
2547 });
2548 assert_eq!(
2549 messages(&context, cx),
2550 vec![
2551 (message_1.id, Role::User, 0..2),
2552 (message_2.id, Role::Assistant, 2..4),
2553 (message_3.id, Role::User, 4..4)
2554 ]
2555 );
2556
2557 let message_4 = context.update(cx, |context, cx| {
2558 context
2559 .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2560 .unwrap()
2561 });
2562 assert_eq!(
2563 messages(&context, cx),
2564 vec![
2565 (message_1.id, Role::User, 0..2),
2566 (message_2.id, Role::Assistant, 2..4),
2567 (message_4.id, Role::User, 4..5),
2568 (message_3.id, Role::User, 5..5),
2569 ]
2570 );
2571
2572 buffer.update(cx, |buffer, cx| {
2573 buffer.edit([(4..4, "C"), (5..5, "D")], None, cx)
2574 });
2575 assert_eq!(
2576 messages(&context, cx),
2577 vec![
2578 (message_1.id, Role::User, 0..2),
2579 (message_2.id, Role::Assistant, 2..4),
2580 (message_4.id, Role::User, 4..6),
2581 (message_3.id, Role::User, 6..7),
2582 ]
2583 );
2584
2585 // Deleting across message boundaries merges the messages.
2586 buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx));
2587 assert_eq!(
2588 messages(&context, cx),
2589 vec![
2590 (message_1.id, Role::User, 0..3),
2591 (message_3.id, Role::User, 3..4),
2592 ]
2593 );
2594
2595 // Undoing the deletion should also undo the merge.
2596 buffer.update(cx, |buffer, cx| buffer.undo(cx));
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 // Redoing the deletion should also redo the merge.
2608 buffer.update(cx, |buffer, cx| buffer.redo(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 // Ensure we can still insert after a merged message.
2618 let message_5 = context.update(cx, |context, cx| {
2619 context
2620 .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
2621 .unwrap()
2622 });
2623 assert_eq!(
2624 messages(&context, cx),
2625 vec![
2626 (message_1.id, Role::User, 0..3),
2627 (message_5.id, Role::System, 3..4),
2628 (message_3.id, Role::User, 4..5)
2629 ]
2630 );
2631 }
2632
2633 #[gpui::test]
2634 fn test_message_splitting(cx: &mut AppContext) {
2635 let settings_store = SettingsStore::test(cx);
2636 cx.set_global(settings_store);
2637 FakeCompletionProvider::setup_test(cx);
2638 assistant_panel::init(cx);
2639 let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2640
2641 let context = cx.new_model(|cx| Context::local(registry, None, cx));
2642 let buffer = context.read(cx).buffer.clone();
2643
2644 let message_1 = context.read(cx).message_anchors[0].clone();
2645 assert_eq!(
2646 messages(&context, cx),
2647 vec![(message_1.id, Role::User, 0..0)]
2648 );
2649
2650 buffer.update(cx, |buffer, cx| {
2651 buffer.edit([(0..0, "aaa\nbbb\nccc\nddd\n")], None, cx)
2652 });
2653
2654 let (_, message_2) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2655 let message_2 = message_2.unwrap();
2656
2657 // We recycle newlines in the middle of a split message
2658 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n");
2659 assert_eq!(
2660 messages(&context, cx),
2661 vec![
2662 (message_1.id, Role::User, 0..4),
2663 (message_2.id, Role::User, 4..16),
2664 ]
2665 );
2666
2667 let (_, message_3) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2668 let message_3 = message_3.unwrap();
2669
2670 // We don't recycle newlines at the end of a split message
2671 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2672 assert_eq!(
2673 messages(&context, cx),
2674 vec![
2675 (message_1.id, Role::User, 0..4),
2676 (message_3.id, Role::User, 4..5),
2677 (message_2.id, Role::User, 5..17),
2678 ]
2679 );
2680
2681 let (_, message_4) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2682 let message_4 = message_4.unwrap();
2683 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2684 assert_eq!(
2685 messages(&context, cx),
2686 vec![
2687 (message_1.id, Role::User, 0..4),
2688 (message_3.id, Role::User, 4..5),
2689 (message_2.id, Role::User, 5..9),
2690 (message_4.id, Role::User, 9..17),
2691 ]
2692 );
2693
2694 let (_, message_5) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2695 let message_5 = message_5.unwrap();
2696 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n");
2697 assert_eq!(
2698 messages(&context, cx),
2699 vec![
2700 (message_1.id, Role::User, 0..4),
2701 (message_3.id, Role::User, 4..5),
2702 (message_2.id, Role::User, 5..9),
2703 (message_4.id, Role::User, 9..10),
2704 (message_5.id, Role::User, 10..18),
2705 ]
2706 );
2707
2708 let (message_6, message_7) =
2709 context.update(cx, |context, cx| context.split_message(14..16, cx));
2710 let message_6 = message_6.unwrap();
2711 let message_7 = message_7.unwrap();
2712 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n");
2713 assert_eq!(
2714 messages(&context, cx),
2715 vec![
2716 (message_1.id, Role::User, 0..4),
2717 (message_3.id, Role::User, 4..5),
2718 (message_2.id, Role::User, 5..9),
2719 (message_4.id, Role::User, 9..10),
2720 (message_5.id, Role::User, 10..14),
2721 (message_6.id, Role::User, 14..17),
2722 (message_7.id, Role::User, 17..19),
2723 ]
2724 );
2725 }
2726
2727 #[gpui::test]
2728 fn test_messages_for_offsets(cx: &mut AppContext) {
2729 let settings_store = SettingsStore::test(cx);
2730 FakeCompletionProvider::setup_test(cx);
2731 cx.set_global(settings_store);
2732 assistant_panel::init(cx);
2733 let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2734 let context = cx.new_model(|cx| Context::local(registry, None, cx));
2735 let buffer = context.read(cx).buffer.clone();
2736
2737 let message_1 = context.read(cx).message_anchors[0].clone();
2738 assert_eq!(
2739 messages(&context, cx),
2740 vec![(message_1.id, Role::User, 0..0)]
2741 );
2742
2743 buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx));
2744 let message_2 = context
2745 .update(cx, |context, cx| {
2746 context.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx)
2747 })
2748 .unwrap();
2749 buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx));
2750
2751 let message_3 = context
2752 .update(cx, |context, cx| {
2753 context.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2754 })
2755 .unwrap();
2756 buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx));
2757
2758 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc");
2759 assert_eq!(
2760 messages(&context, cx),
2761 vec![
2762 (message_1.id, Role::User, 0..4),
2763 (message_2.id, Role::User, 4..8),
2764 (message_3.id, Role::User, 8..11)
2765 ]
2766 );
2767
2768 assert_eq!(
2769 message_ids_for_offsets(&context, &[0, 4, 9], cx),
2770 [message_1.id, message_2.id, message_3.id]
2771 );
2772 assert_eq!(
2773 message_ids_for_offsets(&context, &[0, 1, 11], cx),
2774 [message_1.id, message_3.id]
2775 );
2776
2777 let message_4 = context
2778 .update(cx, |context, cx| {
2779 context.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx)
2780 })
2781 .unwrap();
2782 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n");
2783 assert_eq!(
2784 messages(&context, cx),
2785 vec![
2786 (message_1.id, Role::User, 0..4),
2787 (message_2.id, Role::User, 4..8),
2788 (message_3.id, Role::User, 8..12),
2789 (message_4.id, Role::User, 12..12)
2790 ]
2791 );
2792 assert_eq!(
2793 message_ids_for_offsets(&context, &[0, 4, 8, 12], cx),
2794 [message_1.id, message_2.id, message_3.id, message_4.id]
2795 );
2796
2797 fn message_ids_for_offsets(
2798 context: &Model<Context>,
2799 offsets: &[usize],
2800 cx: &AppContext,
2801 ) -> Vec<MessageId> {
2802 context
2803 .read(cx)
2804 .messages_for_offsets(offsets.iter().copied(), cx)
2805 .into_iter()
2806 .map(|message| message.id)
2807 .collect()
2808 }
2809 }
2810
2811 #[gpui::test]
2812 async fn test_slash_commands(cx: &mut TestAppContext) {
2813 let settings_store = cx.update(SettingsStore::test);
2814 cx.set_global(settings_store);
2815 cx.update(FakeCompletionProvider::setup_test);
2816 cx.update(Project::init_settings);
2817 cx.update(assistant_panel::init);
2818 let fs = FakeFs::new(cx.background_executor.clone());
2819
2820 fs.insert_tree(
2821 "/test",
2822 json!({
2823 "src": {
2824 "lib.rs": "fn one() -> usize { 1 }",
2825 "main.rs": "
2826 use crate::one;
2827 fn main() { one(); }
2828 ".unindent(),
2829 }
2830 }),
2831 )
2832 .await;
2833
2834 let slash_command_registry = cx.update(SlashCommandRegistry::default_global);
2835 slash_command_registry.register_command(file_command::FileSlashCommand, false);
2836 slash_command_registry.register_command(active_command::ActiveSlashCommand, false);
2837
2838 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
2839 let context = cx.new_model(|cx| Context::local(registry.clone(), None, cx));
2840
2841 let output_ranges = Rc::new(RefCell::new(HashSet::default()));
2842 context.update(cx, |_, cx| {
2843 cx.subscribe(&context, {
2844 let ranges = output_ranges.clone();
2845 move |_, _, event, _| match event {
2846 ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
2847 for range in removed {
2848 ranges.borrow_mut().remove(range);
2849 }
2850 for command in updated {
2851 ranges.borrow_mut().insert(command.source_range.clone());
2852 }
2853 }
2854 _ => {}
2855 }
2856 })
2857 .detach();
2858 });
2859
2860 let buffer = context.read_with(cx, |context, _| context.buffer.clone());
2861
2862 // Insert a slash command
2863 buffer.update(cx, |buffer, cx| {
2864 buffer.edit([(0..0, "/file src/lib.rs")], None, cx);
2865 });
2866 assert_text_and_output_ranges(
2867 &buffer,
2868 &output_ranges.borrow(),
2869 "
2870 «/file src/lib.rs»
2871 "
2872 .unindent()
2873 .trim_end(),
2874 cx,
2875 );
2876
2877 // Edit the argument of the slash command.
2878 buffer.update(cx, |buffer, cx| {
2879 let edit_offset = buffer.text().find("lib.rs").unwrap();
2880 buffer.edit([(edit_offset..edit_offset + "lib".len(), "main")], None, cx);
2881 });
2882 assert_text_and_output_ranges(
2883 &buffer,
2884 &output_ranges.borrow(),
2885 "
2886 «/file src/main.rs»
2887 "
2888 .unindent()
2889 .trim_end(),
2890 cx,
2891 );
2892
2893 // Edit the name of the slash command, using one that doesn't exist.
2894 buffer.update(cx, |buffer, cx| {
2895 let edit_offset = buffer.text().find("/file").unwrap();
2896 buffer.edit(
2897 [(edit_offset..edit_offset + "/file".len(), "/unknown")],
2898 None,
2899 cx,
2900 );
2901 });
2902 assert_text_and_output_ranges(
2903 &buffer,
2904 &output_ranges.borrow(),
2905 "
2906 /unknown src/main.rs
2907 "
2908 .unindent()
2909 .trim_end(),
2910 cx,
2911 );
2912
2913 #[track_caller]
2914 fn assert_text_and_output_ranges(
2915 buffer: &Model<Buffer>,
2916 ranges: &HashSet<Range<language::Anchor>>,
2917 expected_marked_text: &str,
2918 cx: &mut TestAppContext,
2919 ) {
2920 let (expected_text, expected_ranges) = marked_text_ranges(expected_marked_text, false);
2921 let (actual_text, actual_ranges) = buffer.update(cx, |buffer, _| {
2922 let mut ranges = ranges
2923 .iter()
2924 .map(|range| range.to_offset(buffer))
2925 .collect::<Vec<_>>();
2926 ranges.sort_by_key(|a| a.start);
2927 (buffer.text(), ranges)
2928 });
2929
2930 assert_eq!(actual_text, expected_text);
2931 assert_eq!(actual_ranges, expected_ranges);
2932 }
2933 }
2934
2935 #[gpui::test]
2936 async fn test_edit_step_parsing(cx: &mut TestAppContext) {
2937 cx.update(prompt_library::init);
2938 let settings_store = cx.update(SettingsStore::test);
2939 cx.set_global(settings_store);
2940 let fake_provider = cx.update(FakeCompletionProvider::setup_test);
2941 cx.update(assistant_panel::init);
2942 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
2943
2944 // Create a new context
2945 let context = cx.new_model(|cx| Context::local(registry.clone(), None, cx));
2946 let buffer = context.read_with(cx, |context, _| context.buffer.clone());
2947
2948 // Simulate user input
2949 let user_message = indoc! {r#"
2950 Please refactor this code:
2951
2952 fn main() {
2953 println!("Hello, World!");
2954 }
2955 "#};
2956 buffer.update(cx, |buffer, cx| {
2957 buffer.edit([(0..0, user_message)], None, cx);
2958 });
2959
2960 // Simulate LLM response with edit steps
2961 let llm_response = indoc! {r#"
2962 Sure, I can help you refactor that code. Here's a step-by-step process:
2963
2964 <step>
2965 First, let's extract the greeting into a separate function:
2966
2967 ```rust
2968 fn greet() {
2969 println!("Hello, World!");
2970 }
2971
2972 fn main() {
2973 greet();
2974 }
2975 ```
2976 </step>
2977
2978 <step>
2979 Now, let's make the greeting customizable:
2980
2981 ```rust
2982 fn greet(name: &str) {
2983 println!("Hello, {}!", name);
2984 }
2985
2986 fn main() {
2987 greet("World");
2988 }
2989 ```
2990 </step>
2991
2992 These changes make the code more modular and flexible.
2993 "#};
2994
2995 // Simulate the assist method to trigger the LLM response
2996 context.update(cx, |context, cx| context.assist(cx));
2997 cx.run_until_parked();
2998
2999 // Retrieve the assistant response message's start from the context
3000 let response_start_row = context.read_with(cx, |context, cx| {
3001 let buffer = context.buffer.read(cx);
3002 context.message_anchors[1].start.to_point(buffer).row
3003 });
3004
3005 // Simulate the LLM completion
3006 fake_provider.send_last_completion_chunk(llm_response.to_string());
3007 fake_provider.finish_last_completion();
3008
3009 // Wait for the completion to be processed
3010 cx.run_until_parked();
3011
3012 // Verify that the edit steps were parsed correctly
3013 context.read_with(cx, |context, cx| {
3014 assert_eq!(
3015 edit_steps(context, cx),
3016 vec![
3017 Point::new(response_start_row + 2, 0)..Point::new(response_start_row + 14, 7),
3018 Point::new(response_start_row + 16, 0)..Point::new(response_start_row + 28, 7),
3019 ]
3020 );
3021 });
3022
3023 fn edit_steps(context: &Context, cx: &AppContext) -> Vec<Range<Point>> {
3024 context
3025 .edit_steps
3026 .iter()
3027 .map(|step| {
3028 let buffer = context.buffer.read(cx);
3029 step.source_range.to_point(buffer)
3030 })
3031 .collect()
3032 }
3033 }
3034
3035 #[test]
3036 fn test_parse_edit_operations() {
3037 let operations = indoc! {r#"
3038 Here are the operations to make all fields of the Canvas struct private:
3039
3040 <operations>
3041 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub pixels" description="Remove pub keyword from pixels field" />
3042 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub size" description="Remove pub keyword from size field" />
3043 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub stride" description="Remove pub keyword from stride field" />
3044 <update path="font-kit/src/canvas.rs" symbol="pub struct Canvas pub format" description="Remove pub keyword from format field" />
3045 </operations>
3046 "#};
3047
3048 let parsed_operations = Context::parse_edit_operations(operations);
3049 assert_eq!(
3050 parsed_operations,
3051 vec![
3052 EditOperation {
3053 path: "font-kit/src/canvas.rs".to_string(),
3054 kind: EditOperationKind::Update {
3055 symbol: "pub struct Canvas pub pixels".to_string(),
3056 description: "Remove pub keyword from pixels field".to_string(),
3057 },
3058 },
3059 EditOperation {
3060 path: "font-kit/src/canvas.rs".to_string(),
3061 kind: EditOperationKind::Update {
3062 symbol: "pub struct Canvas pub size".to_string(),
3063 description: "Remove pub keyword from size field".to_string(),
3064 },
3065 },
3066 EditOperation {
3067 path: "font-kit/src/canvas.rs".to_string(),
3068 kind: EditOperationKind::Update {
3069 symbol: "pub struct Canvas pub stride".to_string(),
3070 description: "Remove pub keyword from stride field".to_string(),
3071 },
3072 },
3073 EditOperation {
3074 path: "font-kit/src/canvas.rs".to_string(),
3075 kind: EditOperationKind::Update {
3076 symbol: "pub struct Canvas pub format".to_string(),
3077 description: "Remove pub keyword from format field".to_string(),
3078 },
3079 },
3080 ]
3081 );
3082 }
3083
3084 #[gpui::test]
3085 async fn test_serialization(cx: &mut TestAppContext) {
3086 let settings_store = cx.update(SettingsStore::test);
3087 cx.set_global(settings_store);
3088 cx.update(FakeCompletionProvider::setup_test);
3089 cx.update(assistant_panel::init);
3090 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3091 let context = cx.new_model(|cx| Context::local(registry.clone(), None, cx));
3092 let buffer = context.read_with(cx, |context, _| context.buffer.clone());
3093 let message_0 = context.read_with(cx, |context, _| context.message_anchors[0].id);
3094 let message_1 = context.update(cx, |context, cx| {
3095 context
3096 .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx)
3097 .unwrap()
3098 });
3099 let message_2 = context.update(cx, |context, cx| {
3100 context
3101 .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3102 .unwrap()
3103 });
3104 buffer.update(cx, |buffer, cx| {
3105 buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx);
3106 buffer.finalize_last_transaction();
3107 });
3108 let _message_3 = context.update(cx, |context, cx| {
3109 context
3110 .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx)
3111 .unwrap()
3112 });
3113 buffer.update(cx, |buffer, cx| buffer.undo(cx));
3114 assert_eq!(buffer.read_with(cx, |buffer, _| buffer.text()), "a\nb\nc\n");
3115 assert_eq!(
3116 cx.read(|cx| messages(&context, cx)),
3117 [
3118 (message_0, Role::User, 0..2),
3119 (message_1.id, Role::Assistant, 2..6),
3120 (message_2.id, Role::System, 6..6),
3121 ]
3122 );
3123
3124 let serialized_context = context.read_with(cx, |context, cx| context.serialize(cx));
3125 let deserialized_context = cx.new_model(|cx| {
3126 Context::deserialize(
3127 serialized_context,
3128 Default::default(),
3129 registry.clone(),
3130 None,
3131 cx,
3132 )
3133 });
3134 let deserialized_buffer =
3135 deserialized_context.read_with(cx, |context, _| context.buffer.clone());
3136 assert_eq!(
3137 deserialized_buffer.read_with(cx, |buffer, _| buffer.text()),
3138 "a\nb\nc\n"
3139 );
3140 assert_eq!(
3141 cx.read(|cx| messages(&deserialized_context, cx)),
3142 [
3143 (message_0, Role::User, 0..2),
3144 (message_1.id, Role::Assistant, 2..6),
3145 (message_2.id, Role::System, 6..6),
3146 ]
3147 );
3148 }
3149
3150 #[gpui::test(iterations = 100)]
3151 async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: StdRng) {
3152 let min_peers = env::var("MIN_PEERS")
3153 .map(|i| i.parse().expect("invalid `MIN_PEERS` variable"))
3154 .unwrap_or(2);
3155 let max_peers = env::var("MAX_PEERS")
3156 .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
3157 .unwrap_or(5);
3158 let operations = env::var("OPERATIONS")
3159 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3160 .unwrap_or(50);
3161
3162 let settings_store = cx.update(SettingsStore::test);
3163 cx.set_global(settings_store);
3164 cx.update(FakeCompletionProvider::setup_test);
3165 cx.update(assistant_panel::init);
3166 let slash_commands = cx.update(SlashCommandRegistry::default_global);
3167 slash_commands.register_command(FakeSlashCommand("cmd-1".into()), false);
3168 slash_commands.register_command(FakeSlashCommand("cmd-2".into()), false);
3169 slash_commands.register_command(FakeSlashCommand("cmd-3".into()), false);
3170
3171 let registry = Arc::new(LanguageRegistry::test(cx.background_executor.clone()));
3172 let network = Arc::new(Mutex::new(Network::new(rng.clone())));
3173 let mut contexts = Vec::new();
3174
3175 let num_peers = rng.gen_range(min_peers..=max_peers);
3176 let context_id = ContextId::new();
3177 for i in 0..num_peers {
3178 let context = cx.new_model(|cx| {
3179 Context::new(
3180 context_id.clone(),
3181 i as ReplicaId,
3182 language::Capability::ReadWrite,
3183 registry.clone(),
3184 None,
3185 cx,
3186 )
3187 });
3188
3189 cx.update(|cx| {
3190 cx.subscribe(&context, {
3191 let network = network.clone();
3192 move |_, event, _| {
3193 if let ContextEvent::Operation(op) = event {
3194 network
3195 .lock()
3196 .broadcast(i as ReplicaId, vec![op.to_proto()]);
3197 }
3198 }
3199 })
3200 .detach();
3201 });
3202
3203 contexts.push(context);
3204 network.lock().add_peer(i as ReplicaId);
3205 }
3206
3207 let mut mutation_count = operations;
3208
3209 while mutation_count > 0
3210 || !network.lock().is_idle()
3211 || network.lock().contains_disconnected_peers()
3212 {
3213 let context_index = rng.gen_range(0..contexts.len());
3214 let context = &contexts[context_index];
3215
3216 match rng.gen_range(0..100) {
3217 0..=29 if mutation_count > 0 => {
3218 log::info!("Context {}: edit buffer", context_index);
3219 context.update(cx, |context, cx| {
3220 context
3221 .buffer
3222 .update(cx, |buffer, cx| buffer.randomly_edit(&mut rng, 1, cx));
3223 });
3224 mutation_count -= 1;
3225 }
3226 30..=44 if mutation_count > 0 => {
3227 context.update(cx, |context, cx| {
3228 let range = context.buffer.read(cx).random_byte_range(0, &mut rng);
3229 log::info!("Context {}: split message at {:?}", context_index, range);
3230 context.split_message(range, cx);
3231 });
3232 mutation_count -= 1;
3233 }
3234 45..=59 if mutation_count > 0 => {
3235 context.update(cx, |context, cx| {
3236 if let Some(message) = context.messages(cx).choose(&mut rng) {
3237 let role = *[Role::User, Role::Assistant, Role::System]
3238 .choose(&mut rng)
3239 .unwrap();
3240 log::info!(
3241 "Context {}: insert message after {:?} with {:?}",
3242 context_index,
3243 message.id,
3244 role
3245 );
3246 context.insert_message_after(message.id, role, MessageStatus::Done, cx);
3247 }
3248 });
3249 mutation_count -= 1;
3250 }
3251 60..=74 if mutation_count > 0 => {
3252 context.update(cx, |context, cx| {
3253 let command_text = "/".to_string()
3254 + slash_commands
3255 .command_names()
3256 .choose(&mut rng)
3257 .unwrap()
3258 .clone()
3259 .as_ref();
3260
3261 let command_range = context.buffer.update(cx, |buffer, cx| {
3262 let offset = buffer.random_byte_range(0, &mut rng).start;
3263 buffer.edit(
3264 [(offset..offset, format!("\n{}\n", command_text))],
3265 None,
3266 cx,
3267 );
3268 offset + 1..offset + 1 + command_text.len()
3269 });
3270
3271 let output_len = rng.gen_range(1..=10);
3272 let output_text = RandomCharIter::new(&mut rng)
3273 .filter(|c| *c != '\r')
3274 .take(output_len)
3275 .collect::<String>();
3276
3277 let num_sections = rng.gen_range(0..=3);
3278 let mut sections = Vec::with_capacity(num_sections);
3279 for _ in 0..num_sections {
3280 let section_start = rng.gen_range(0..output_len);
3281 let section_end = rng.gen_range(section_start..=output_len);
3282 sections.push(SlashCommandOutputSection {
3283 range: section_start..section_end,
3284 icon: ui::IconName::Ai,
3285 label: "section".into(),
3286 });
3287 }
3288
3289 log::info!(
3290 "Context {}: insert slash command output at {:?} with {:?}",
3291 context_index,
3292 command_range,
3293 sections
3294 );
3295
3296 let command_range =
3297 context.buffer.read(cx).anchor_after(command_range.start)
3298 ..context.buffer.read(cx).anchor_after(command_range.end);
3299 context.insert_command_output(
3300 command_range,
3301 Task::ready(Ok(SlashCommandOutput {
3302 text: output_text,
3303 sections,
3304 run_commands_in_text: false,
3305 })),
3306 true,
3307 cx,
3308 );
3309 });
3310 cx.run_until_parked();
3311 mutation_count -= 1;
3312 }
3313 75..=84 if mutation_count > 0 => {
3314 context.update(cx, |context, cx| {
3315 if let Some(message) = context.messages(cx).choose(&mut rng) {
3316 let new_status = match rng.gen_range(0..3) {
3317 0 => MessageStatus::Done,
3318 1 => MessageStatus::Pending,
3319 _ => MessageStatus::Error(SharedString::from("Random error")),
3320 };
3321 log::info!(
3322 "Context {}: update message {:?} status to {:?}",
3323 context_index,
3324 message.id,
3325 new_status
3326 );
3327 context.update_metadata(message.id, cx, |metadata| {
3328 metadata.status = new_status;
3329 });
3330 }
3331 });
3332 mutation_count -= 1;
3333 }
3334 _ => {
3335 let replica_id = context_index as ReplicaId;
3336 if network.lock().is_disconnected(replica_id) {
3337 network.lock().reconnect_peer(replica_id, 0);
3338
3339 let (ops_to_send, ops_to_receive) = cx.read(|cx| {
3340 let host_context = &contexts[0].read(cx);
3341 let guest_context = context.read(cx);
3342 (
3343 guest_context.serialize_ops(&host_context.version(cx), cx),
3344 host_context.serialize_ops(&guest_context.version(cx), cx),
3345 )
3346 });
3347 let ops_to_send = ops_to_send.await;
3348 let ops_to_receive = ops_to_receive
3349 .await
3350 .into_iter()
3351 .map(ContextOperation::from_proto)
3352 .collect::<Result<Vec<_>>>()
3353 .unwrap();
3354 log::info!(
3355 "Context {}: reconnecting. Sent {} operations, received {} operations",
3356 context_index,
3357 ops_to_send.len(),
3358 ops_to_receive.len()
3359 );
3360
3361 network.lock().broadcast(replica_id, ops_to_send);
3362 context
3363 .update(cx, |context, cx| context.apply_ops(ops_to_receive, cx))
3364 .unwrap();
3365 } else if rng.gen_bool(0.1) && replica_id != 0 {
3366 log::info!("Context {}: disconnecting", context_index);
3367 network.lock().disconnect_peer(replica_id);
3368 } else if network.lock().has_unreceived(replica_id) {
3369 log::info!("Context {}: applying operations", context_index);
3370 let ops = network.lock().receive(replica_id);
3371 let ops = ops
3372 .into_iter()
3373 .map(ContextOperation::from_proto)
3374 .collect::<Result<Vec<_>>>()
3375 .unwrap();
3376 context
3377 .update(cx, |context, cx| context.apply_ops(ops, cx))
3378 .unwrap();
3379 }
3380 }
3381 }
3382 }
3383
3384 cx.read(|cx| {
3385 let first_context = contexts[0].read(cx);
3386 for context in &contexts[1..] {
3387 let context = context.read(cx);
3388 assert!(context.pending_ops.is_empty());
3389 assert_eq!(
3390 context.buffer.read(cx).text(),
3391 first_context.buffer.read(cx).text(),
3392 "Context {} text != Context 0 text",
3393 context.buffer.read(cx).replica_id()
3394 );
3395 assert_eq!(
3396 context.message_anchors,
3397 first_context.message_anchors,
3398 "Context {} messages != Context 0 messages",
3399 context.buffer.read(cx).replica_id()
3400 );
3401 assert_eq!(
3402 context.messages_metadata,
3403 first_context.messages_metadata,
3404 "Context {} message metadata != Context 0 message metadata",
3405 context.buffer.read(cx).replica_id()
3406 );
3407 assert_eq!(
3408 context.slash_command_output_sections,
3409 first_context.slash_command_output_sections,
3410 "Context {} slash command output sections != Context 0 slash command output sections",
3411 context.buffer.read(cx).replica_id()
3412 );
3413 }
3414 });
3415 }
3416
3417 fn messages(context: &Model<Context>, cx: &AppContext) -> Vec<(MessageId, Role, Range<usize>)> {
3418 context
3419 .read(cx)
3420 .messages(cx)
3421 .map(|message| (message.id, message.role, message.offset_range))
3422 .collect()
3423 }
3424
3425 #[derive(Clone)]
3426 struct FakeSlashCommand(String);
3427
3428 impl SlashCommand for FakeSlashCommand {
3429 fn name(&self) -> String {
3430 self.0.clone()
3431 }
3432
3433 fn description(&self) -> String {
3434 format!("Fake slash command: {}", self.0)
3435 }
3436
3437 fn menu_text(&self) -> String {
3438 format!("Run fake command: {}", self.0)
3439 }
3440
3441 fn complete_argument(
3442 self: Arc<Self>,
3443 _query: String,
3444 _cancel: Arc<AtomicBool>,
3445 _workspace: Option<WeakView<Workspace>>,
3446 _cx: &mut AppContext,
3447 ) -> Task<Result<Vec<ArgumentCompletion>>> {
3448 Task::ready(Ok(vec![]))
3449 }
3450
3451 fn requires_argument(&self) -> bool {
3452 false
3453 }
3454
3455 fn run(
3456 self: Arc<Self>,
3457 _argument: Option<&str>,
3458 _workspace: WeakView<Workspace>,
3459 _delegate: Arc<dyn LspAdapterDelegate>,
3460 _cx: &mut WindowContext,
3461 ) -> Task<Result<SlashCommandOutput>> {
3462 Task::ready(Ok(SlashCommandOutput {
3463 text: format!("Executed fake command: {}", self.0),
3464 sections: vec![],
3465 run_commands_in_text: false,
3466 }))
3467 }
3468 }
3469}