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