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