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