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