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