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