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