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,
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<Entity<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<Entity<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<Entity<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,
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<Entity<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 = range.start == language::Anchor::MIN
1151 || range.start == language::Anchor::MAX
1152 || version.observed(range.start.timestamp);
1153 let observed_end = range.end == language::Anchor::MIN
1154 || range.end == language::Anchor::MAX
1155 || version.observed(range.end.timestamp);
1156 observed_start && observed_end
1157 }
1158
1159 fn push_op(&mut self, op: TextThreadOperation, cx: &mut Context<Self>) {
1160 self.operations.push(op.clone());
1161 cx.emit(TextThreadEvent::Operation(op));
1162 }
1163
1164 pub fn buffer(&self) -> &Entity<Buffer> {
1165 &self.buffer
1166 }
1167
1168 pub fn language_registry(&self) -> Arc<LanguageRegistry> {
1169 self.language_registry.clone()
1170 }
1171
1172 pub fn project(&self) -> Option<Entity<Project>> {
1173 self.project.clone()
1174 }
1175
1176 pub fn prompt_builder(&self) -> Arc<PromptBuilder> {
1177 self.prompt_builder.clone()
1178 }
1179
1180 pub fn path(&self) -> Option<&Arc<Path>> {
1181 self.path.as_ref()
1182 }
1183
1184 pub fn summary(&self) -> &TextThreadSummary {
1185 &self.summary
1186 }
1187
1188 pub fn parsed_slash_commands(&self) -> &[ParsedSlashCommand] {
1189 &self.parsed_slash_commands
1190 }
1191
1192 pub fn invoked_slash_command(
1193 &self,
1194 command_id: &InvokedSlashCommandId,
1195 ) -> Option<&InvokedSlashCommand> {
1196 self.invoked_slash_commands.get(command_id)
1197 }
1198
1199 pub fn slash_command_output_sections(&self) -> &[SlashCommandOutputSection<language::Anchor>] {
1200 &self.slash_command_output_sections
1201 }
1202
1203 pub fn thought_process_output_sections(
1204 &self,
1205 ) -> &[ThoughtProcessOutputSection<language::Anchor>] {
1206 &self.thought_process_output_sections
1207 }
1208
1209 pub fn contains_files(&self, cx: &App) -> bool {
1210 let buffer = self.buffer.read(cx);
1211 self.slash_command_output_sections.iter().any(|section| {
1212 section.is_valid(buffer)
1213 && section
1214 .metadata
1215 .as_ref()
1216 .and_then(|metadata| {
1217 serde_json::from_value::<FileCommandMetadata>(metadata.clone()).ok()
1218 })
1219 .is_some()
1220 })
1221 }
1222
1223 fn set_language(&mut self, cx: &mut Context<Self>) {
1224 let markdown = self.language_registry.language_for_name("Markdown");
1225 cx.spawn(async move |this, cx| {
1226 let markdown = markdown.await?;
1227 this.update(cx, |this, cx| {
1228 this.buffer
1229 .update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx));
1230 })
1231 })
1232 .detach_and_log_err(cx);
1233 }
1234
1235 fn handle_buffer_event(
1236 &mut self,
1237 _: Entity<Buffer>,
1238 event: &language::BufferEvent,
1239 cx: &mut Context<Self>,
1240 ) {
1241 match event {
1242 language::BufferEvent::Operation {
1243 operation,
1244 is_local: true,
1245 } => cx.emit(TextThreadEvent::Operation(
1246 TextThreadOperation::BufferOperation(operation.clone()),
1247 )),
1248 language::BufferEvent::Edited => {
1249 self.count_remaining_tokens(cx);
1250 self.reparse(cx);
1251 cx.emit(TextThreadEvent::MessagesEdited);
1252 }
1253 _ => {}
1254 }
1255 }
1256
1257 pub fn token_count(&self) -> Option<u64> {
1258 self.token_count
1259 }
1260
1261 pub(crate) fn count_remaining_tokens(&mut self, cx: &mut Context<Self>) {
1262 // Assume it will be a Chat request, even though that takes fewer tokens (and risks going over the limit),
1263 // because otherwise you see in the UI that your empty message has a bunch of tokens already used.
1264 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1265 return;
1266 };
1267 let request = self.to_completion_request(Some(&model.model), cx);
1268 let debounce = self.token_count.is_some();
1269 self.pending_token_count = cx.spawn(async move |this, cx| {
1270 async move {
1271 if debounce {
1272 cx.background_executor()
1273 .timer(Duration::from_millis(200))
1274 .await;
1275 }
1276
1277 let token_count = cx
1278 .update(|cx| model.model.count_tokens(request, cx))?
1279 .await?;
1280 this.update(cx, |this, cx| {
1281 this.token_count = Some(token_count);
1282 this.start_cache_warming(&model.model, cx);
1283 cx.notify()
1284 })
1285 }
1286 .log_err()
1287 .await
1288 });
1289 }
1290
1291 pub fn mark_cache_anchors(
1292 &mut self,
1293 cache_configuration: &Option<LanguageModelCacheConfiguration>,
1294 speculative: bool,
1295 cx: &mut Context<Self>,
1296 ) -> bool {
1297 let cache_configuration =
1298 cache_configuration
1299 .as_ref()
1300 .unwrap_or(&LanguageModelCacheConfiguration {
1301 max_cache_anchors: 0,
1302 should_speculate: false,
1303 min_total_token: 0,
1304 });
1305
1306 let messages: Vec<Message> = self.messages(cx).collect();
1307
1308 let mut sorted_messages = messages.clone();
1309 if speculative {
1310 // Avoid caching the last message if this is a speculative cache fetch as
1311 // it's likely to change.
1312 sorted_messages.pop();
1313 }
1314 sorted_messages.retain(|m| m.role == Role::User);
1315 sorted_messages.sort_by(|a, b| b.offset_range.len().cmp(&a.offset_range.len()));
1316
1317 let cache_anchors = if self.token_count.unwrap_or(0) < cache_configuration.min_total_token {
1318 // If we have't hit the minimum threshold to enable caching, don't cache anything.
1319 0
1320 } else {
1321 // Save 1 anchor for the inline assistant to use.
1322 max(cache_configuration.max_cache_anchors, 1) - 1
1323 };
1324 sorted_messages.truncate(cache_anchors);
1325
1326 let anchors: HashSet<MessageId> = sorted_messages
1327 .into_iter()
1328 .map(|message| message.id)
1329 .collect();
1330
1331 let buffer = self.buffer.read(cx).snapshot();
1332 let invalidated_caches: HashSet<MessageId> = messages
1333 .iter()
1334 .scan(false, |encountered_invalid, message| {
1335 let message_id = message.id;
1336 let is_invalid = self
1337 .messages_metadata
1338 .get(&message_id)
1339 .is_none_or(|metadata| {
1340 !metadata.is_cache_valid(&buffer, &message.offset_range)
1341 || *encountered_invalid
1342 });
1343 *encountered_invalid |= is_invalid;
1344 Some(if is_invalid { Some(message_id) } else { None })
1345 })
1346 .flatten()
1347 .collect();
1348
1349 let last_anchor = messages.iter().rev().find_map(|message| {
1350 if anchors.contains(&message.id) {
1351 Some(message.id)
1352 } else {
1353 None
1354 }
1355 });
1356
1357 let mut new_anchor_needs_caching = false;
1358 let current_version = &buffer.version;
1359 // If we have no anchors, mark all messages as not being cached.
1360 let mut hit_last_anchor = last_anchor.is_none();
1361
1362 for message in messages.iter() {
1363 if hit_last_anchor {
1364 self.update_metadata(message.id, cx, |metadata| metadata.cache = None);
1365 continue;
1366 }
1367
1368 if let Some(last_anchor) = last_anchor
1369 && message.id == last_anchor
1370 {
1371 hit_last_anchor = true;
1372 }
1373
1374 new_anchor_needs_caching = new_anchor_needs_caching
1375 || (invalidated_caches.contains(&message.id) && anchors.contains(&message.id));
1376
1377 self.update_metadata(message.id, cx, |metadata| {
1378 let cache_status = if invalidated_caches.contains(&message.id) {
1379 CacheStatus::Pending
1380 } else {
1381 metadata
1382 .cache
1383 .as_ref()
1384 .map_or(CacheStatus::Pending, |cm| cm.status.clone())
1385 };
1386 metadata.cache = Some(MessageCacheMetadata {
1387 is_anchor: anchors.contains(&message.id),
1388 is_final_anchor: hit_last_anchor,
1389 status: cache_status,
1390 cached_at: current_version.clone(),
1391 });
1392 });
1393 }
1394 new_anchor_needs_caching
1395 }
1396
1397 fn start_cache_warming(&mut self, model: &Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1398 let cache_configuration = model.cache_configuration();
1399
1400 if !self.mark_cache_anchors(&cache_configuration, true, cx) {
1401 return;
1402 }
1403 if !self.pending_completions.is_empty() {
1404 return;
1405 }
1406 if let Some(cache_configuration) = cache_configuration
1407 && !cache_configuration.should_speculate
1408 {
1409 return;
1410 }
1411
1412 let request = {
1413 let mut req = self.to_completion_request(Some(model), cx);
1414 // Skip the last message because it's likely to change and
1415 // therefore would be a waste to cache.
1416 req.messages.pop();
1417 req.messages.push(LanguageModelRequestMessage {
1418 role: Role::User,
1419 content: vec!["Respond only with OK, nothing else.".into()],
1420 cache: false,
1421 reasoning_details: None,
1422 });
1423 req
1424 };
1425
1426 let model = Arc::clone(model);
1427 self.pending_cache_warming_task = cx.spawn(async move |this, cx| {
1428 async move {
1429 match model.stream_completion(request, cx).await {
1430 Ok(mut stream) => {
1431 stream.next().await;
1432 log::info!("Cache warming completed successfully");
1433 }
1434 Err(e) => {
1435 log::warn!("Cache warming failed: {}", e);
1436 }
1437 };
1438 this.update(cx, |this, cx| {
1439 this.update_cache_status_for_completion(cx);
1440 })
1441 .ok();
1442 anyhow::Ok(())
1443 }
1444 .log_err()
1445 .await
1446 });
1447 }
1448
1449 pub fn update_cache_status_for_completion(&mut self, cx: &mut Context<Self>) {
1450 let cached_message_ids: Vec<MessageId> = self
1451 .messages_metadata
1452 .iter()
1453 .filter_map(|(message_id, metadata)| {
1454 metadata.cache.as_ref().and_then(|cache| {
1455 if cache.status == CacheStatus::Pending {
1456 Some(*message_id)
1457 } else {
1458 None
1459 }
1460 })
1461 })
1462 .collect();
1463
1464 for message_id in cached_message_ids {
1465 self.update_metadata(message_id, cx, |metadata| {
1466 if let Some(cache) = &mut metadata.cache {
1467 cache.status = CacheStatus::Cached;
1468 }
1469 });
1470 }
1471 cx.notify();
1472 }
1473
1474 pub fn reparse(&mut self, cx: &mut Context<Self>) {
1475 let buffer = self.buffer.read(cx).text_snapshot();
1476 let mut row_ranges = self
1477 .edits_since_last_parse
1478 .consume()
1479 .into_iter()
1480 .map(|edit| {
1481 let start_row = buffer.offset_to_point(edit.new.start).row;
1482 let end_row = buffer.offset_to_point(edit.new.end).row + 1;
1483 start_row..end_row
1484 })
1485 .peekable();
1486
1487 let mut removed_parsed_slash_command_ranges = Vec::new();
1488 let mut updated_parsed_slash_commands = Vec::new();
1489 while let Some(mut row_range) = row_ranges.next() {
1490 while let Some(next_row_range) = row_ranges.peek() {
1491 if row_range.end >= next_row_range.start {
1492 row_range.end = next_row_range.end;
1493 row_ranges.next();
1494 } else {
1495 break;
1496 }
1497 }
1498
1499 let start = buffer.anchor_before(Point::new(row_range.start, 0));
1500 let end = buffer.anchor_after(Point::new(
1501 row_range.end - 1,
1502 buffer.line_len(row_range.end - 1),
1503 ));
1504
1505 self.reparse_slash_commands_in_range(
1506 start..end,
1507 &buffer,
1508 &mut updated_parsed_slash_commands,
1509 &mut removed_parsed_slash_command_ranges,
1510 cx,
1511 );
1512 self.invalidate_pending_slash_commands(&buffer, cx);
1513 }
1514
1515 if !updated_parsed_slash_commands.is_empty()
1516 || !removed_parsed_slash_command_ranges.is_empty()
1517 {
1518 cx.emit(TextThreadEvent::ParsedSlashCommandsUpdated {
1519 removed: removed_parsed_slash_command_ranges,
1520 updated: updated_parsed_slash_commands,
1521 });
1522 }
1523 }
1524
1525 fn reparse_slash_commands_in_range(
1526 &mut self,
1527 range: Range<text::Anchor>,
1528 buffer: &BufferSnapshot,
1529 updated: &mut Vec<ParsedSlashCommand>,
1530 removed: &mut Vec<Range<text::Anchor>>,
1531 cx: &App,
1532 ) {
1533 let old_range = self.pending_command_indices_for_range(range.clone(), cx);
1534
1535 let mut new_commands = Vec::new();
1536 let mut lines = buffer.text_for_range(range).lines();
1537 let mut offset = lines.offset();
1538 while let Some(line) = lines.next() {
1539 if let Some(command_line) = SlashCommandLine::parse(line) {
1540 let name = &line[command_line.name.clone()];
1541 let arguments = command_line
1542 .arguments
1543 .iter()
1544 .filter_map(|argument_range| {
1545 if argument_range.is_empty() {
1546 None
1547 } else {
1548 line.get(argument_range.clone())
1549 }
1550 })
1551 .map(ToOwned::to_owned)
1552 .collect::<SmallVec<_>>();
1553 if let Some(command) = self.slash_commands.command(name, cx)
1554 && (!command.requires_argument() || !arguments.is_empty())
1555 {
1556 let start_ix = offset + command_line.name.start - 1;
1557 let end_ix = offset
1558 + command_line
1559 .arguments
1560 .last()
1561 .map_or(command_line.name.end, |argument| argument.end);
1562 let source_range = buffer.anchor_after(start_ix)..buffer.anchor_after(end_ix);
1563 let pending_command = ParsedSlashCommand {
1564 name: name.to_string(),
1565 arguments,
1566 source_range,
1567 status: PendingSlashCommandStatus::Idle,
1568 };
1569 updated.push(pending_command.clone());
1570 new_commands.push(pending_command);
1571 }
1572 }
1573
1574 offset = lines.offset();
1575 }
1576
1577 let removed_commands = self.parsed_slash_commands.splice(old_range, new_commands);
1578 removed.extend(removed_commands.map(|command| command.source_range));
1579 }
1580
1581 fn invalidate_pending_slash_commands(
1582 &mut self,
1583 buffer: &BufferSnapshot,
1584 cx: &mut Context<Self>,
1585 ) {
1586 let mut invalidated_command_ids = Vec::new();
1587 for (&command_id, command) in self.invoked_slash_commands.iter_mut() {
1588 if !matches!(command.status, InvokedSlashCommandStatus::Finished)
1589 && (!command.range.start.is_valid(buffer) || !command.range.end.is_valid(buffer))
1590 {
1591 command.status = InvokedSlashCommandStatus::Finished;
1592 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1593 invalidated_command_ids.push(command_id);
1594 }
1595 }
1596
1597 for command_id in invalidated_command_ids {
1598 let version = self.version.clone();
1599 let timestamp = self.next_timestamp();
1600 self.push_op(
1601 TextThreadOperation::SlashCommandFinished {
1602 id: command_id,
1603 timestamp,
1604 error_message: None,
1605 version: version.clone(),
1606 },
1607 cx,
1608 );
1609 }
1610 }
1611
1612 pub fn pending_command_for_position(
1613 &mut self,
1614 position: language::Anchor,
1615 cx: &mut Context<Self>,
1616 ) -> Option<&mut ParsedSlashCommand> {
1617 let buffer = self.buffer.read(cx);
1618 match self
1619 .parsed_slash_commands
1620 .binary_search_by(|probe| probe.source_range.end.cmp(&position, buffer))
1621 {
1622 Ok(ix) => Some(&mut self.parsed_slash_commands[ix]),
1623 Err(ix) => {
1624 let cmd = self.parsed_slash_commands.get_mut(ix)?;
1625 if position.cmp(&cmd.source_range.start, buffer).is_ge()
1626 && position.cmp(&cmd.source_range.end, buffer).is_le()
1627 {
1628 Some(cmd)
1629 } else {
1630 None
1631 }
1632 }
1633 }
1634 }
1635
1636 pub fn pending_commands_for_range(
1637 &self,
1638 range: Range<language::Anchor>,
1639 cx: &App,
1640 ) -> &[ParsedSlashCommand] {
1641 let range = self.pending_command_indices_for_range(range, cx);
1642 &self.parsed_slash_commands[range]
1643 }
1644
1645 fn pending_command_indices_for_range(
1646 &self,
1647 range: Range<language::Anchor>,
1648 cx: &App,
1649 ) -> Range<usize> {
1650 self.indices_intersecting_buffer_range(&self.parsed_slash_commands, range, cx)
1651 }
1652
1653 fn indices_intersecting_buffer_range<T: ContextAnnotation>(
1654 &self,
1655 all_annotations: &[T],
1656 range: Range<language::Anchor>,
1657 cx: &App,
1658 ) -> Range<usize> {
1659 let buffer = self.buffer.read(cx);
1660 let start_ix = match all_annotations
1661 .binary_search_by(|probe| probe.range().end.cmp(&range.start, buffer))
1662 {
1663 Ok(ix) | Err(ix) => ix,
1664 };
1665 let end_ix = match all_annotations
1666 .binary_search_by(|probe| probe.range().start.cmp(&range.end, buffer))
1667 {
1668 Ok(ix) => ix + 1,
1669 Err(ix) => ix,
1670 };
1671 start_ix..end_ix
1672 }
1673
1674 pub fn insert_command_output(
1675 &mut self,
1676 command_source_range: Range<language::Anchor>,
1677 name: &str,
1678 output: Task<SlashCommandResult>,
1679 ensure_trailing_newline: bool,
1680 cx: &mut Context<Self>,
1681 ) {
1682 let version = self.version.clone();
1683 let command_id = InvokedSlashCommandId(self.next_timestamp());
1684
1685 const PENDING_OUTPUT_END_MARKER: &str = "…";
1686
1687 let (command_range, command_source_range, insert_position, first_transaction) =
1688 self.buffer.update(cx, |buffer, cx| {
1689 let command_source_range = command_source_range.to_offset(buffer);
1690 let mut insertion = format!("\n{PENDING_OUTPUT_END_MARKER}");
1691 if ensure_trailing_newline {
1692 insertion.push('\n');
1693 }
1694
1695 buffer.finalize_last_transaction();
1696 buffer.start_transaction();
1697 buffer.edit(
1698 [(
1699 command_source_range.end..command_source_range.end,
1700 insertion,
1701 )],
1702 None,
1703 cx,
1704 );
1705 let first_transaction = buffer.end_transaction(cx).unwrap();
1706 buffer.finalize_last_transaction();
1707
1708 let insert_position = buffer.anchor_after(command_source_range.end + 1);
1709 let command_range = buffer.anchor_after(command_source_range.start)
1710 ..buffer.anchor_before(
1711 command_source_range.end + 1 + PENDING_OUTPUT_END_MARKER.len(),
1712 );
1713 let command_source_range = buffer.anchor_before(command_source_range.start)
1714 ..buffer.anchor_before(command_source_range.end + 1);
1715 (
1716 command_range,
1717 command_source_range,
1718 insert_position,
1719 first_transaction,
1720 )
1721 });
1722 self.reparse(cx);
1723
1724 let insert_output_task = cx.spawn(async move |this, cx| {
1725 let run_command = async {
1726 let mut stream = output.await?;
1727
1728 struct PendingSection {
1729 start: language::Anchor,
1730 icon: IconName,
1731 label: SharedString,
1732 metadata: Option<serde_json::Value>,
1733 }
1734
1735 let mut pending_section_stack: Vec<PendingSection> = Vec::new();
1736 let mut last_role: Option<Role> = None;
1737 let mut last_section_range = None;
1738
1739 while let Some(event) = stream.next().await {
1740 let event = event?;
1741 this.update(cx, |this, cx| {
1742 this.buffer.update(cx, |buffer, _cx| {
1743 buffer.finalize_last_transaction();
1744 buffer.start_transaction()
1745 });
1746
1747 match event {
1748 SlashCommandEvent::StartMessage {
1749 role,
1750 merge_same_roles,
1751 } => {
1752 if !merge_same_roles && Some(role) != last_role {
1753 let buffer = this.buffer.read(cx);
1754 let offset = insert_position.to_offset(buffer);
1755 this.insert_message_at_offset(
1756 offset,
1757 role,
1758 MessageStatus::Pending,
1759 cx,
1760 );
1761 }
1762
1763 last_role = Some(role);
1764 }
1765 SlashCommandEvent::StartSection {
1766 icon,
1767 label,
1768 metadata,
1769 } => {
1770 this.buffer.update(cx, |buffer, cx| {
1771 let insert_point = insert_position.to_point(buffer);
1772 if insert_point.column > 0 {
1773 buffer.edit([(insert_point..insert_point, "\n")], None, cx);
1774 }
1775
1776 pending_section_stack.push(PendingSection {
1777 start: buffer.anchor_before(insert_position),
1778 icon,
1779 label,
1780 metadata,
1781 });
1782 });
1783 }
1784 SlashCommandEvent::Content(SlashCommandContent::Text {
1785 text,
1786 run_commands_in_text,
1787 }) => {
1788 let start = this.buffer.read(cx).anchor_before(insert_position);
1789
1790 this.buffer.update(cx, |buffer, cx| {
1791 buffer.edit(
1792 [(insert_position..insert_position, text)],
1793 None,
1794 cx,
1795 )
1796 });
1797
1798 let end = this.buffer.read(cx).anchor_before(insert_position);
1799 if run_commands_in_text
1800 && let Some(invoked_slash_command) =
1801 this.invoked_slash_commands.get_mut(&command_id)
1802 {
1803 invoked_slash_command
1804 .run_commands_in_ranges
1805 .push(start..end);
1806 }
1807 }
1808 SlashCommandEvent::EndSection => {
1809 if let Some(pending_section) = pending_section_stack.pop() {
1810 let offset_range = (pending_section.start..insert_position)
1811 .to_offset(this.buffer.read(cx));
1812 if !offset_range.is_empty() {
1813 let range = this.buffer.update(cx, |buffer, _cx| {
1814 buffer.anchor_after(offset_range.start)
1815 ..buffer.anchor_before(offset_range.end)
1816 });
1817 this.insert_slash_command_output_section(
1818 SlashCommandOutputSection {
1819 range: range.clone(),
1820 icon: pending_section.icon,
1821 label: pending_section.label,
1822 metadata: pending_section.metadata,
1823 },
1824 cx,
1825 );
1826 last_section_range = Some(range);
1827 }
1828 }
1829 }
1830 }
1831
1832 this.buffer.update(cx, |buffer, cx| {
1833 if let Some(event_transaction) = buffer.end_transaction(cx) {
1834 buffer.merge_transactions(event_transaction, first_transaction);
1835 }
1836 });
1837 })?;
1838 }
1839
1840 this.update(cx, |this, cx| {
1841 this.buffer.update(cx, |buffer, cx| {
1842 buffer.finalize_last_transaction();
1843 buffer.start_transaction();
1844
1845 let mut deletions = vec![(command_source_range.to_offset(buffer), "")];
1846 let insert_position = insert_position.to_offset(buffer);
1847 let command_range_end = command_range.end.to_offset(buffer);
1848
1849 if buffer.contains_str_at(insert_position, PENDING_OUTPUT_END_MARKER) {
1850 deletions.push((
1851 insert_position..insert_position + PENDING_OUTPUT_END_MARKER.len(),
1852 "",
1853 ));
1854 }
1855
1856 if ensure_trailing_newline
1857 && buffer
1858 .chars_at(command_range_end)
1859 .next()
1860 .is_some_and(|c| c == '\n')
1861 {
1862 if let Some((prev_char, '\n')) =
1863 buffer.reversed_chars_at(insert_position).next_tuple()
1864 && last_section_range.is_none_or(|last_section_range| {
1865 !last_section_range
1866 .to_offset(buffer)
1867 .contains(&(insert_position - prev_char.len_utf8()))
1868 })
1869 {
1870 deletions.push((command_range_end..command_range_end + 1, ""));
1871 }
1872 }
1873
1874 buffer.edit(deletions, None, cx);
1875
1876 if let Some(deletion_transaction) = buffer.end_transaction(cx) {
1877 buffer.merge_transactions(deletion_transaction, first_transaction);
1878 }
1879 });
1880 })?;
1881
1882 debug_assert!(pending_section_stack.is_empty());
1883
1884 anyhow::Ok(())
1885 };
1886
1887 let command_result = run_command.await;
1888
1889 this.update(cx, |this, cx| {
1890 let version = this.version.clone();
1891 let timestamp = this.next_timestamp();
1892 let Some(invoked_slash_command) = this.invoked_slash_commands.get_mut(&command_id)
1893 else {
1894 return;
1895 };
1896 let mut error_message = None;
1897 match command_result {
1898 Ok(()) => {
1899 invoked_slash_command.status = InvokedSlashCommandStatus::Finished;
1900 }
1901 Err(error) => {
1902 let message = error.to_string();
1903 invoked_slash_command.status =
1904 InvokedSlashCommandStatus::Error(message.clone().into());
1905 error_message = Some(message);
1906 }
1907 }
1908
1909 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1910 this.push_op(
1911 TextThreadOperation::SlashCommandFinished {
1912 id: command_id,
1913 timestamp,
1914 error_message,
1915 version,
1916 },
1917 cx,
1918 );
1919 })
1920 .ok();
1921 });
1922
1923 self.invoked_slash_commands.insert(
1924 command_id,
1925 InvokedSlashCommand {
1926 name: name.to_string().into(),
1927 range: command_range.clone(),
1928 run_commands_in_ranges: Vec::new(),
1929 status: InvokedSlashCommandStatus::Running(insert_output_task),
1930 transaction: Some(first_transaction),
1931 timestamp: command_id.0,
1932 },
1933 );
1934 cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1935 self.push_op(
1936 TextThreadOperation::SlashCommandStarted {
1937 id: command_id,
1938 output_range: command_range,
1939 name: name.to_string(),
1940 version,
1941 },
1942 cx,
1943 );
1944 }
1945
1946 fn insert_slash_command_output_section(
1947 &mut self,
1948 section: SlashCommandOutputSection<language::Anchor>,
1949 cx: &mut Context<Self>,
1950 ) {
1951 let buffer = self.buffer.read(cx);
1952 let insertion_ix = match self
1953 .slash_command_output_sections
1954 .binary_search_by(|probe| probe.range.cmp(§ion.range, buffer))
1955 {
1956 Ok(ix) | Err(ix) => ix,
1957 };
1958 self.slash_command_output_sections
1959 .insert(insertion_ix, section.clone());
1960 cx.emit(TextThreadEvent::SlashCommandOutputSectionAdded {
1961 section: section.clone(),
1962 });
1963 let version = self.version.clone();
1964 let timestamp = self.next_timestamp();
1965 self.push_op(
1966 TextThreadOperation::SlashCommandOutputSectionAdded {
1967 timestamp,
1968 section,
1969 version,
1970 },
1971 cx,
1972 );
1973 }
1974
1975 fn insert_thought_process_output_section(
1976 &mut self,
1977 section: ThoughtProcessOutputSection<language::Anchor>,
1978 cx: &mut Context<Self>,
1979 ) {
1980 let buffer = self.buffer.read(cx);
1981 let insertion_ix = match self
1982 .thought_process_output_sections
1983 .binary_search_by(|probe| probe.range.cmp(§ion.range, buffer))
1984 {
1985 Ok(ix) | Err(ix) => ix,
1986 };
1987 self.thought_process_output_sections
1988 .insert(insertion_ix, section.clone());
1989 // cx.emit(ContextEvent::ThoughtProcessOutputSectionAdded {
1990 // section: section.clone(),
1991 // });
1992 let version = self.version.clone();
1993 let timestamp = self.next_timestamp();
1994 self.push_op(
1995 TextThreadOperation::ThoughtProcessOutputSectionAdded {
1996 timestamp,
1997 section,
1998 version,
1999 },
2000 cx,
2001 );
2002 }
2003
2004 pub fn completion_provider_changed(&mut self, cx: &mut Context<Self>) {
2005 self.count_remaining_tokens(cx);
2006 }
2007
2008 fn get_last_valid_message_id(&self, cx: &Context<Self>) -> Option<MessageId> {
2009 self.message_anchors.iter().rev().find_map(|message| {
2010 message
2011 .start
2012 .is_valid(self.buffer.read(cx))
2013 .then_some(message.id)
2014 })
2015 }
2016
2017 pub fn assist(&mut self, cx: &mut Context<Self>) -> Option<MessageAnchor> {
2018 let model_registry = LanguageModelRegistry::read_global(cx);
2019 let model = model_registry.default_model()?;
2020 let last_message_id = self.get_last_valid_message_id(cx)?;
2021
2022 if !model.provider.is_authenticated(cx) {
2023 log::info!("completion provider has no credentials");
2024 return None;
2025 }
2026
2027 let model = model.model;
2028
2029 // Compute which messages to cache, including the last one.
2030 self.mark_cache_anchors(&model.cache_configuration(), false, cx);
2031
2032 let request = self.to_completion_request(Some(&model), cx);
2033
2034 let assistant_message = self
2035 .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
2036 .unwrap();
2037
2038 // Queue up the user's next reply.
2039 let user_message = self
2040 .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
2041 .unwrap();
2042
2043 let pending_completion_id = post_inc(&mut self.completion_count);
2044
2045 let task = cx.spawn({
2046 async move |this, cx| {
2047 let stream = model.stream_completion(request, cx);
2048 let assistant_message_id = assistant_message.id;
2049 let mut response_latency = None;
2050 let stream_completion = async {
2051 let request_start = Instant::now();
2052 let mut events = stream.await?;
2053 let mut stop_reason = StopReason::EndTurn;
2054 let mut thought_process_stack = Vec::new();
2055
2056 const THOUGHT_PROCESS_START_MARKER: &str = "<think>\n";
2057 const THOUGHT_PROCESS_END_MARKER: &str = "\n</think>";
2058
2059 while let Some(event) = events.next().await {
2060 if response_latency.is_none() {
2061 response_latency = Some(request_start.elapsed());
2062 }
2063 let event = event?;
2064
2065 let mut context_event = None;
2066 let mut thought_process_output_section = None;
2067
2068 this.update(cx, |this, cx| {
2069 let message_ix = this
2070 .message_anchors
2071 .iter()
2072 .position(|message| message.id == assistant_message_id)?;
2073 this.buffer.update(cx, |buffer, cx| {
2074 let message_old_end_offset = this.message_anchors[message_ix + 1..]
2075 .iter()
2076 .find(|message| message.start.is_valid(buffer))
2077 .map_or(buffer.len(), |message| {
2078 message.start.to_offset(buffer).saturating_sub(1)
2079 });
2080
2081 match event {
2082 LanguageModelCompletionEvent::Started |
2083 LanguageModelCompletionEvent::Queued {..} |
2084 LanguageModelCompletionEvent::ToolUseLimitReached { .. } => {}
2085 LanguageModelCompletionEvent::UsageUpdated { amount, limit } => {
2086 this.update_model_request_usage(
2087 amount as u32,
2088 limit,
2089 cx,
2090 );
2091 }
2092 LanguageModelCompletionEvent::StartMessage { .. } => {}
2093 LanguageModelCompletionEvent::ReasoningDetails(_) => {
2094 // ReasoningDetails are metadata (signatures, encrypted data, format info)
2095 // used for request/response validation, not UI content.
2096 // The displayable thinking text is already handled by the Thinking event.
2097 }
2098 LanguageModelCompletionEvent::Stop(reason) => {
2099 stop_reason = reason;
2100 }
2101 LanguageModelCompletionEvent::Thinking { text: chunk, .. } => {
2102 if thought_process_stack.is_empty() {
2103 let start =
2104 buffer.anchor_before(message_old_end_offset);
2105 thought_process_stack.push(start);
2106 let chunk =
2107 format!("{THOUGHT_PROCESS_START_MARKER}{chunk}{THOUGHT_PROCESS_END_MARKER}");
2108 let chunk_len = chunk.len();
2109 buffer.edit(
2110 [(
2111 message_old_end_offset..message_old_end_offset,
2112 chunk,
2113 )],
2114 None,
2115 cx,
2116 );
2117 let end = buffer
2118 .anchor_before(message_old_end_offset + chunk_len);
2119 context_event = Some(
2120 TextThreadEvent::StartedThoughtProcess(start..end),
2121 );
2122 } else {
2123 // This ensures that all the thinking chunks are inserted inside the thinking tag
2124 let insertion_position =
2125 message_old_end_offset - THOUGHT_PROCESS_END_MARKER.len();
2126 buffer.edit(
2127 [(insertion_position..insertion_position, chunk)],
2128 None,
2129 cx,
2130 );
2131 }
2132 }
2133 LanguageModelCompletionEvent::RedactedThinking { .. } => {},
2134 LanguageModelCompletionEvent::Text(mut chunk) => {
2135 if let Some(start) = thought_process_stack.pop() {
2136 let end = buffer.anchor_before(message_old_end_offset);
2137 context_event =
2138 Some(TextThreadEvent::EndedThoughtProcess(end));
2139 thought_process_output_section =
2140 Some(ThoughtProcessOutputSection {
2141 range: start..end,
2142 });
2143 chunk.insert_str(0, "\n\n");
2144 }
2145
2146 buffer.edit(
2147 [(
2148 message_old_end_offset..message_old_end_offset,
2149 chunk,
2150 )],
2151 None,
2152 cx,
2153 );
2154 }
2155 LanguageModelCompletionEvent::ToolUse(_) |
2156 LanguageModelCompletionEvent::ToolUseJsonParseError { .. } |
2157 LanguageModelCompletionEvent::UsageUpdate(_) => {}
2158 }
2159 });
2160
2161 if let Some(section) = thought_process_output_section.take() {
2162 this.insert_thought_process_output_section(section, cx);
2163 }
2164 if let Some(context_event) = context_event.take() {
2165 cx.emit(context_event);
2166 }
2167
2168 cx.emit(TextThreadEvent::StreamedCompletion);
2169
2170 Some(())
2171 })?;
2172 smol::future::yield_now().await;
2173 }
2174 this.update(cx, |this, cx| {
2175 this.pending_completions
2176 .retain(|completion| completion.id != pending_completion_id);
2177 this.summarize(false, cx);
2178 this.update_cache_status_for_completion(cx);
2179 })?;
2180
2181 anyhow::Ok(stop_reason)
2182 };
2183
2184 let result = stream_completion.await;
2185
2186 this.update(cx, |this, cx| {
2187 let error_message = if let Some(error) = result.as_ref().err() {
2188 if error.is::<PaymentRequiredError>() {
2189 cx.emit(TextThreadEvent::ShowPaymentRequiredError);
2190 this.update_metadata(assistant_message_id, cx, |metadata| {
2191 metadata.status = MessageStatus::Canceled;
2192 });
2193 Some(error.to_string())
2194 } else {
2195 let error_message = error
2196 .chain()
2197 .map(|err| err.to_string())
2198 .collect::<Vec<_>>()
2199 .join("\n");
2200 cx.emit(TextThreadEvent::ShowAssistError(SharedString::from(
2201 error_message.clone(),
2202 )));
2203 this.update_metadata(assistant_message_id, cx, |metadata| {
2204 metadata.status =
2205 MessageStatus::Error(SharedString::from(error_message.clone()));
2206 });
2207 Some(error_message)
2208 }
2209 } else {
2210 this.update_metadata(assistant_message_id, cx, |metadata| {
2211 metadata.status = MessageStatus::Done;
2212 });
2213 None
2214 };
2215
2216 let language_name = this
2217 .buffer
2218 .read(cx)
2219 .language()
2220 .map(|language| language.name());
2221 report_assistant_event(
2222 AssistantEventData {
2223 conversation_id: Some(this.id.0.clone()),
2224 kind: AssistantKind::Panel,
2225 phase: AssistantPhase::Response,
2226 message_id: None,
2227 model: model.telemetry_id(),
2228 model_provider: model.provider_id().to_string(),
2229 response_latency,
2230 error_message,
2231 language_name: language_name.map(|name| name.to_proto()),
2232 },
2233 this.telemetry.clone(),
2234 cx.http_client(),
2235 model.api_key(cx),
2236 cx.background_executor(),
2237 );
2238
2239 if let Ok(stop_reason) = result {
2240 match stop_reason {
2241 StopReason::ToolUse => {}
2242 StopReason::EndTurn => {}
2243 StopReason::MaxTokens => {}
2244 StopReason::Refusal => {}
2245 }
2246 }
2247 })
2248 .ok();
2249 }
2250 });
2251
2252 self.pending_completions.push(PendingCompletion {
2253 id: pending_completion_id,
2254 assistant_message_id: assistant_message.id,
2255 _task: task,
2256 });
2257
2258 Some(user_message)
2259 }
2260
2261 pub fn to_xml(&self, cx: &App) -> String {
2262 let mut output = String::new();
2263 let buffer = self.buffer.read(cx);
2264 for message in self.messages(cx) {
2265 if message.status != MessageStatus::Done {
2266 continue;
2267 }
2268
2269 writeln!(&mut output, "<{}>", message.role).unwrap();
2270 for chunk in buffer.text_for_range(message.offset_range) {
2271 output.push_str(chunk);
2272 }
2273 if !output.ends_with('\n') {
2274 output.push('\n');
2275 }
2276 writeln!(&mut output, "</{}>", message.role).unwrap();
2277 }
2278 output
2279 }
2280
2281 pub fn to_completion_request(
2282 &self,
2283 model: Option<&Arc<dyn LanguageModel>>,
2284 cx: &App,
2285 ) -> LanguageModelRequest {
2286 let buffer = self.buffer.read(cx);
2287
2288 let mut contents = self.contents(cx).peekable();
2289
2290 fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2291 let text: String = buffer.text_for_range(range).collect();
2292 if text.trim().is_empty() {
2293 None
2294 } else {
2295 Some(text)
2296 }
2297 }
2298
2299 let mut completion_request = LanguageModelRequest {
2300 thread_id: None,
2301 prompt_id: None,
2302 intent: Some(CompletionIntent::UserPrompt),
2303 mode: None,
2304 messages: Vec::new(),
2305 tools: Vec::new(),
2306 tool_choice: None,
2307 stop: Vec::new(),
2308 temperature: model.and_then(|model| AgentSettings::temperature_for_model(model, cx)),
2309 thinking_allowed: true,
2310 };
2311 for message in self.messages(cx) {
2312 if message.status != MessageStatus::Done {
2313 continue;
2314 }
2315
2316 let mut offset = message.offset_range.start;
2317 let mut request_message = LanguageModelRequestMessage {
2318 role: message.role,
2319 content: Vec::new(),
2320 cache: message.cache.as_ref().is_some_and(|cache| cache.is_anchor),
2321 reasoning_details: None,
2322 };
2323
2324 while let Some(content) = contents.peek() {
2325 if content
2326 .range()
2327 .end
2328 .cmp(&message.anchor_range.end, buffer)
2329 .is_lt()
2330 {
2331 let content = contents.next().unwrap();
2332 let range = content.range().to_offset(buffer);
2333 request_message.content.extend(
2334 collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2335 );
2336
2337 match content {
2338 Content::Image { image, .. } => {
2339 if let Some(image) = image.clone().now_or_never().flatten() {
2340 request_message
2341 .content
2342 .push(language_model::MessageContent::Image(image));
2343 }
2344 }
2345 }
2346
2347 offset = range.end;
2348 } else {
2349 break;
2350 }
2351 }
2352
2353 request_message.content.extend(
2354 collect_text_content(buffer, offset..message.offset_range.end)
2355 .map(MessageContent::Text),
2356 );
2357
2358 if !request_message.contents_empty() {
2359 completion_request.messages.push(request_message);
2360 }
2361 }
2362 let supports_burn_mode = if let Some(model) = model {
2363 model.supports_burn_mode()
2364 } else {
2365 false
2366 };
2367
2368 if supports_burn_mode {
2369 completion_request.mode = Some(self.completion_mode.into());
2370 }
2371 completion_request
2372 }
2373
2374 pub fn cancel_last_assist(&mut self, cx: &mut Context<Self>) -> bool {
2375 if let Some(pending_completion) = self.pending_completions.pop() {
2376 self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2377 if metadata.status == MessageStatus::Pending {
2378 metadata.status = MessageStatus::Canceled;
2379 }
2380 });
2381 true
2382 } else {
2383 false
2384 }
2385 }
2386
2387 pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2388 for id in &ids {
2389 if let Some(metadata) = self.messages_metadata.get(id) {
2390 let role = metadata.role.cycle();
2391 self.update_metadata(*id, cx, |metadata| metadata.role = role);
2392 }
2393 }
2394
2395 self.message_roles_updated(ids, cx);
2396 }
2397
2398 fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2399 let mut ranges = Vec::new();
2400 for message in self.messages(cx) {
2401 if ids.contains(&message.id) {
2402 ranges.push(message.anchor_range.clone());
2403 }
2404 }
2405 }
2406
2407 pub fn update_metadata(
2408 &mut self,
2409 id: MessageId,
2410 cx: &mut Context<Self>,
2411 f: impl FnOnce(&mut MessageMetadata),
2412 ) {
2413 let version = self.version.clone();
2414 let timestamp = self.next_timestamp();
2415 if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2416 f(metadata);
2417 metadata.timestamp = timestamp;
2418 let operation = TextThreadOperation::UpdateMessage {
2419 message_id: id,
2420 metadata: metadata.clone(),
2421 version,
2422 };
2423 self.push_op(operation, cx);
2424 cx.emit(TextThreadEvent::MessagesEdited);
2425 cx.notify();
2426 }
2427 }
2428
2429 pub fn insert_message_after(
2430 &mut self,
2431 message_id: MessageId,
2432 role: Role,
2433 status: MessageStatus,
2434 cx: &mut Context<Self>,
2435 ) -> Option<MessageAnchor> {
2436 if let Some(prev_message_ix) = self
2437 .message_anchors
2438 .iter()
2439 .position(|message| message.id == message_id)
2440 {
2441 // Find the next valid message after the one we were given.
2442 let mut next_message_ix = prev_message_ix + 1;
2443 while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2444 if next_message.start.is_valid(self.buffer.read(cx)) {
2445 break;
2446 }
2447 next_message_ix += 1;
2448 }
2449
2450 let buffer = self.buffer.read(cx);
2451 let offset = self
2452 .message_anchors
2453 .get(next_message_ix)
2454 .map_or(buffer.len(), |message| {
2455 buffer.clip_offset(message.start.to_previous_offset(buffer), Bias::Left)
2456 });
2457 Some(self.insert_message_at_offset(offset, role, status, cx))
2458 } else {
2459 None
2460 }
2461 }
2462
2463 fn insert_message_at_offset(
2464 &mut self,
2465 offset: usize,
2466 role: Role,
2467 status: MessageStatus,
2468 cx: &mut Context<Self>,
2469 ) -> MessageAnchor {
2470 let start = self.buffer.update(cx, |buffer, cx| {
2471 buffer.edit([(offset..offset, "\n")], None, cx);
2472 buffer.anchor_before(offset + 1)
2473 });
2474
2475 let version = self.version.clone();
2476 let anchor = MessageAnchor {
2477 id: MessageId(self.next_timestamp()),
2478 start,
2479 };
2480 let metadata = MessageMetadata {
2481 role,
2482 status,
2483 timestamp: anchor.id.0,
2484 cache: None,
2485 };
2486 self.insert_message(anchor.clone(), metadata.clone(), cx);
2487 self.push_op(
2488 TextThreadOperation::InsertMessage {
2489 anchor: anchor.clone(),
2490 metadata,
2491 version,
2492 },
2493 cx,
2494 );
2495 anchor
2496 }
2497
2498 pub fn insert_content(&mut self, content: Content, cx: &mut Context<Self>) {
2499 let buffer = self.buffer.read(cx);
2500 let insertion_ix = match self
2501 .contents
2502 .binary_search_by(|probe| probe.cmp(&content, buffer))
2503 {
2504 Ok(ix) => {
2505 self.contents.remove(ix);
2506 ix
2507 }
2508 Err(ix) => ix,
2509 };
2510 self.contents.insert(insertion_ix, content);
2511 cx.emit(TextThreadEvent::MessagesEdited);
2512 }
2513
2514 pub fn contents<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Content> {
2515 let buffer = self.buffer.read(cx);
2516 self.contents
2517 .iter()
2518 .filter(|content| {
2519 let range = content.range();
2520 range.start.is_valid(buffer) && range.end.is_valid(buffer)
2521 })
2522 .cloned()
2523 }
2524
2525 pub fn split_message(
2526 &mut self,
2527 range: Range<usize>,
2528 cx: &mut Context<Self>,
2529 ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2530 let start_message = self.message_for_offset(range.start, cx);
2531 let end_message = self.message_for_offset(range.end, cx);
2532 if let Some((start_message, end_message)) = start_message.zip(end_message) {
2533 // Prevent splitting when range spans multiple messages.
2534 if start_message.id != end_message.id {
2535 return (None, None);
2536 }
2537
2538 let message = start_message;
2539 let at_end = range.end >= message.offset_range.end.saturating_sub(1);
2540 let role_after = if range.start == range.end || at_end {
2541 Role::User
2542 } else {
2543 message.role
2544 };
2545 let role = message.role;
2546 let mut edited_buffer = false;
2547
2548 let mut suffix_start = None;
2549
2550 // TODO: why did this start panicking?
2551 if range.start > message.offset_range.start
2552 && range.end < message.offset_range.end.saturating_sub(1)
2553 {
2554 if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2555 suffix_start = Some(range.end + 1);
2556 } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2557 suffix_start = Some(range.end);
2558 }
2559 }
2560
2561 let version = self.version.clone();
2562 let suffix = if let Some(suffix_start) = suffix_start {
2563 MessageAnchor {
2564 id: MessageId(self.next_timestamp()),
2565 start: self.buffer.read(cx).anchor_before(suffix_start),
2566 }
2567 } else {
2568 self.buffer.update(cx, |buffer, cx| {
2569 buffer.edit([(range.end..range.end, "\n")], None, cx);
2570 });
2571 edited_buffer = true;
2572 MessageAnchor {
2573 id: MessageId(self.next_timestamp()),
2574 start: self.buffer.read(cx).anchor_before(range.end + 1),
2575 }
2576 };
2577
2578 let suffix_metadata = MessageMetadata {
2579 role: role_after,
2580 status: MessageStatus::Done,
2581 timestamp: suffix.id.0,
2582 cache: None,
2583 };
2584 self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2585 self.push_op(
2586 TextThreadOperation::InsertMessage {
2587 anchor: suffix.clone(),
2588 metadata: suffix_metadata,
2589 version,
2590 },
2591 cx,
2592 );
2593
2594 let new_messages =
2595 if range.start == range.end || range.start == message.offset_range.start {
2596 (None, Some(suffix))
2597 } else {
2598 let mut prefix_end = None;
2599 if range.start > message.offset_range.start
2600 && range.end < message.offset_range.end - 1
2601 {
2602 if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2603 prefix_end = Some(range.start + 1);
2604 } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2605 == Some('\n')
2606 {
2607 prefix_end = Some(range.start);
2608 }
2609 }
2610
2611 let version = self.version.clone();
2612 let selection = if let Some(prefix_end) = prefix_end {
2613 MessageAnchor {
2614 id: MessageId(self.next_timestamp()),
2615 start: self.buffer.read(cx).anchor_before(prefix_end),
2616 }
2617 } else {
2618 self.buffer.update(cx, |buffer, cx| {
2619 buffer.edit([(range.start..range.start, "\n")], None, cx)
2620 });
2621 edited_buffer = true;
2622 MessageAnchor {
2623 id: MessageId(self.next_timestamp()),
2624 start: self.buffer.read(cx).anchor_before(range.end + 1),
2625 }
2626 };
2627
2628 let selection_metadata = MessageMetadata {
2629 role,
2630 status: MessageStatus::Done,
2631 timestamp: selection.id.0,
2632 cache: None,
2633 };
2634 self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2635 self.push_op(
2636 TextThreadOperation::InsertMessage {
2637 anchor: selection.clone(),
2638 metadata: selection_metadata,
2639 version,
2640 },
2641 cx,
2642 );
2643
2644 (Some(selection), Some(suffix))
2645 };
2646
2647 if !edited_buffer {
2648 cx.emit(TextThreadEvent::MessagesEdited);
2649 }
2650 new_messages
2651 } else {
2652 (None, None)
2653 }
2654 }
2655
2656 fn insert_message(
2657 &mut self,
2658 new_anchor: MessageAnchor,
2659 new_metadata: MessageMetadata,
2660 cx: &mut Context<Self>,
2661 ) {
2662 cx.emit(TextThreadEvent::MessagesEdited);
2663
2664 self.messages_metadata.insert(new_anchor.id, new_metadata);
2665
2666 let buffer = self.buffer.read(cx);
2667 let insertion_ix = self
2668 .message_anchors
2669 .iter()
2670 .position(|anchor| {
2671 let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2672 comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2673 })
2674 .unwrap_or(self.message_anchors.len());
2675 self.message_anchors.insert(insertion_ix, new_anchor);
2676 }
2677
2678 pub fn summarize(&mut self, mut replace_old: bool, cx: &mut Context<Self>) {
2679 let Some(model) = LanguageModelRegistry::read_global(cx).thread_summary_model() else {
2680 return;
2681 };
2682
2683 if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_pending()) {
2684 if !model.provider.is_authenticated(cx) {
2685 return;
2686 }
2687
2688 let mut request = self.to_completion_request(Some(&model.model), cx);
2689 request.messages.push(LanguageModelRequestMessage {
2690 role: Role::User,
2691 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2692 cache: false,
2693 reasoning_details: None,
2694 });
2695
2696 // If there is no summary, it is set with `done: false` so that "Loading Summary…" can
2697 // be displayed.
2698 match self.summary {
2699 TextThreadSummary::Pending | TextThreadSummary::Error => {
2700 self.summary = TextThreadSummary::Content(TextThreadSummaryContent {
2701 text: "".to_string(),
2702 done: false,
2703 timestamp: clock::Lamport::MIN,
2704 });
2705 replace_old = true;
2706 }
2707 TextThreadSummary::Content(_) => {}
2708 }
2709
2710 self.summary_task = cx.spawn(async move |this, cx| {
2711 let result = async {
2712 let stream = model.model.stream_completion_text(request, cx);
2713 let mut messages = stream.await?;
2714
2715 let mut replaced = !replace_old;
2716 while let Some(message) = messages.stream.next().await {
2717 let text = message?;
2718 let mut lines = text.lines();
2719 this.update(cx, |this, cx| {
2720 let version = this.version.clone();
2721 let timestamp = this.next_timestamp();
2722 let summary = this.summary.content_or_set_empty();
2723 if !replaced && replace_old {
2724 summary.text.clear();
2725 replaced = true;
2726 }
2727 summary.text.extend(lines.next());
2728 summary.timestamp = timestamp;
2729 let operation = TextThreadOperation::UpdateSummary {
2730 summary: summary.clone(),
2731 version,
2732 };
2733 this.push_op(operation, cx);
2734 cx.emit(TextThreadEvent::SummaryChanged);
2735 cx.emit(TextThreadEvent::SummaryGenerated);
2736 })?;
2737
2738 // Stop if the LLM generated multiple lines.
2739 if lines.next().is_some() {
2740 break;
2741 }
2742 }
2743
2744 this.read_with(cx, |this, _cx| {
2745 if let Some(summary) = this.summary.content()
2746 && summary.text.is_empty()
2747 {
2748 bail!("Model generated an empty summary");
2749 }
2750 Ok(())
2751 })??;
2752
2753 this.update(cx, |this, cx| {
2754 let version = this.version.clone();
2755 let timestamp = this.next_timestamp();
2756 if let Some(summary) = this.summary.content_as_mut() {
2757 summary.done = true;
2758 summary.timestamp = timestamp;
2759 let operation = TextThreadOperation::UpdateSummary {
2760 summary: summary.clone(),
2761 version,
2762 };
2763 this.push_op(operation, cx);
2764 cx.emit(TextThreadEvent::SummaryChanged);
2765 cx.emit(TextThreadEvent::SummaryGenerated);
2766 }
2767 })?;
2768
2769 anyhow::Ok(())
2770 }
2771 .await;
2772
2773 if let Err(err) = result {
2774 this.update(cx, |this, cx| {
2775 this.summary = TextThreadSummary::Error;
2776 cx.emit(TextThreadEvent::SummaryChanged);
2777 })
2778 .log_err();
2779 log::error!("Error generating context summary: {}", err);
2780 }
2781
2782 Some(())
2783 });
2784 }
2785 }
2786
2787 fn message_for_offset(&self, offset: usize, cx: &App) -> Option<Message> {
2788 self.messages_for_offsets([offset], cx).pop()
2789 }
2790
2791 pub fn messages_for_offsets(
2792 &self,
2793 offsets: impl IntoIterator<Item = usize>,
2794 cx: &App,
2795 ) -> Vec<Message> {
2796 let mut result = Vec::new();
2797
2798 let mut messages = self.messages(cx).peekable();
2799 let mut offsets = offsets.into_iter().peekable();
2800 let mut current_message = messages.next();
2801 while let Some(offset) = offsets.next() {
2802 // Locate the message that contains the offset.
2803 while current_message.as_ref().is_some_and(|message| {
2804 !message.offset_range.contains(&offset) && messages.peek().is_some()
2805 }) {
2806 current_message = messages.next();
2807 }
2808 let Some(message) = current_message.as_ref() else {
2809 break;
2810 };
2811
2812 // Skip offsets that are in the same message.
2813 while offsets.peek().is_some_and(|offset| {
2814 message.offset_range.contains(offset) || messages.peek().is_none()
2815 }) {
2816 offsets.next();
2817 }
2818
2819 result.push(message.clone());
2820 }
2821 result
2822 }
2823
2824 fn messages_from_anchors<'a>(
2825 &'a self,
2826 message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2827 cx: &'a App,
2828 ) -> impl 'a + Iterator<Item = Message> {
2829 let buffer = self.buffer.read(cx);
2830
2831 Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2832 }
2833
2834 pub fn messages<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Message> {
2835 self.messages_from_anchors(self.message_anchors.iter(), cx)
2836 }
2837
2838 pub fn messages_from_iters<'a>(
2839 buffer: &'a Buffer,
2840 metadata: &'a HashMap<MessageId, MessageMetadata>,
2841 messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2842 ) -> impl 'a + Iterator<Item = Message> {
2843 let mut messages = messages.peekable();
2844
2845 iter::from_fn(move || {
2846 if let Some((start_ix, message_anchor)) = messages.next() {
2847 let metadata = metadata.get(&message_anchor.id)?;
2848
2849 let message_start = message_anchor.start.to_offset(buffer);
2850 let mut message_end = None;
2851 let mut end_ix = start_ix;
2852 while let Some((_, next_message)) = messages.peek() {
2853 if next_message.start.is_valid(buffer) {
2854 message_end = Some(next_message.start);
2855 break;
2856 } else {
2857 end_ix += 1;
2858 messages.next();
2859 }
2860 }
2861 let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2862 let message_end = message_end_anchor.to_offset(buffer);
2863
2864 return Some(Message {
2865 index_range: start_ix..end_ix,
2866 offset_range: message_start..message_end,
2867 anchor_range: message_anchor.start..message_end_anchor,
2868 id: message_anchor.id,
2869 role: metadata.role,
2870 status: metadata.status.clone(),
2871 cache: metadata.cache.clone(),
2872 });
2873 }
2874 None
2875 })
2876 }
2877
2878 pub fn save(
2879 &mut self,
2880 debounce: Option<Duration>,
2881 fs: Arc<dyn Fs>,
2882 cx: &mut Context<TextThread>,
2883 ) {
2884 if self.replica_id() != ReplicaId::default() {
2885 // Prevent saving a remote context for now.
2886 return;
2887 }
2888
2889 self.pending_save = cx.spawn(async move |this, cx| {
2890 if let Some(debounce) = debounce {
2891 cx.background_executor().timer(debounce).await;
2892 }
2893
2894 let (old_path, summary) = this.read_with(cx, |this, _| {
2895 let path = this.path.clone();
2896 let summary = if let Some(summary) = this.summary.content() {
2897 if summary.done {
2898 Some(summary.text.clone())
2899 } else {
2900 None
2901 }
2902 } else {
2903 None
2904 };
2905 (path, summary)
2906 })?;
2907
2908 if let Some(summary) = summary {
2909 let context = this.read_with(cx, |this, cx| this.serialize(cx))?;
2910 let mut discriminant = 1;
2911 let mut new_path;
2912 loop {
2913 new_path = text_threads_dir().join(&format!(
2914 "{} - {}.zed.json",
2915 summary.trim(),
2916 discriminant
2917 ));
2918 if fs.is_file(&new_path).await {
2919 discriminant += 1;
2920 } else {
2921 break;
2922 }
2923 }
2924
2925 fs.create_dir(text_threads_dir().as_ref()).await?;
2926
2927 // rename before write ensures that only one file exists
2928 if let Some(old_path) = old_path.as_ref()
2929 && new_path.as_path() != old_path.as_ref()
2930 {
2931 fs.rename(
2932 old_path,
2933 &new_path,
2934 RenameOptions {
2935 overwrite: true,
2936 ignore_if_exists: true,
2937 },
2938 )
2939 .await?;
2940 }
2941
2942 // update path before write in case it fails
2943 this.update(cx, {
2944 let new_path: Arc<Path> = new_path.clone().into();
2945 move |this, cx| {
2946 this.path = Some(new_path.clone());
2947 cx.emit(TextThreadEvent::PathChanged { old_path, new_path });
2948 }
2949 })
2950 .ok();
2951
2952 fs.atomic_write(new_path, serde_json::to_string(&context).unwrap())
2953 .await?;
2954 }
2955
2956 Ok(())
2957 });
2958 }
2959
2960 pub fn set_custom_summary(&mut self, custom_summary: String, cx: &mut Context<Self>) {
2961 let timestamp = self.next_timestamp();
2962 let summary = self.summary.content_or_set_empty();
2963 summary.timestamp = timestamp;
2964 summary.done = true;
2965 summary.text = custom_summary;
2966 cx.emit(TextThreadEvent::SummaryChanged);
2967 }
2968
2969 fn update_model_request_usage(&self, amount: u32, limit: UsageLimit, cx: &mut App) {
2970 let Some(project) = &self.project else {
2971 return;
2972 };
2973 project.read(cx).user_store().update(cx, |user_store, cx| {
2974 user_store.update_model_request_usage(
2975 ModelRequestUsage(RequestUsage {
2976 amount: amount as i32,
2977 limit,
2978 }),
2979 cx,
2980 )
2981 });
2982 }
2983}
2984
2985#[derive(Debug, Default)]
2986pub struct TextThreadVersion {
2987 text_thread: clock::Global,
2988 buffer: clock::Global,
2989}
2990
2991impl TextThreadVersion {
2992 pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2993 Self {
2994 text_thread: language::proto::deserialize_version(&proto.context_version),
2995 buffer: language::proto::deserialize_version(&proto.buffer_version),
2996 }
2997 }
2998
2999 pub fn to_proto(&self, context_id: TextThreadId) -> proto::ContextVersion {
3000 proto::ContextVersion {
3001 context_id: context_id.to_proto(),
3002 context_version: language::proto::serialize_version(&self.text_thread),
3003 buffer_version: language::proto::serialize_version(&self.buffer),
3004 }
3005 }
3006}
3007
3008#[derive(Debug, Clone)]
3009pub struct ParsedSlashCommand {
3010 pub name: String,
3011 pub arguments: SmallVec<[String; 3]>,
3012 pub status: PendingSlashCommandStatus,
3013 pub source_range: Range<language::Anchor>,
3014}
3015
3016#[derive(Debug)]
3017pub struct InvokedSlashCommand {
3018 pub name: SharedString,
3019 pub range: Range<language::Anchor>,
3020 pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
3021 pub status: InvokedSlashCommandStatus,
3022 pub transaction: Option<language::TransactionId>,
3023 timestamp: clock::Lamport,
3024}
3025
3026#[derive(Debug)]
3027pub enum InvokedSlashCommandStatus {
3028 Running(Task<()>),
3029 Error(SharedString),
3030 Finished,
3031}
3032
3033#[derive(Debug, Clone)]
3034pub enum PendingSlashCommandStatus {
3035 Idle,
3036 Running { _task: Shared<Task<()>> },
3037 Error(String),
3038}
3039
3040#[derive(Debug, Clone)]
3041pub struct PendingToolUse {
3042 pub id: LanguageModelToolUseId,
3043 pub name: String,
3044 pub input: serde_json::Value,
3045 pub status: PendingToolUseStatus,
3046 pub source_range: Range<language::Anchor>,
3047}
3048
3049#[derive(Debug, Clone)]
3050pub enum PendingToolUseStatus {
3051 Idle,
3052 Running { _task: Shared<Task<()>> },
3053 Error(String),
3054}
3055
3056impl PendingToolUseStatus {
3057 pub fn is_idle(&self) -> bool {
3058 matches!(self, PendingToolUseStatus::Idle)
3059 }
3060}
3061
3062#[derive(Serialize, Deserialize)]
3063pub struct SavedMessage {
3064 pub id: MessageId,
3065 pub start: usize,
3066 pub metadata: MessageMetadata,
3067}
3068
3069#[derive(Serialize, Deserialize)]
3070pub struct SavedTextThread {
3071 pub id: Option<TextThreadId>,
3072 pub zed: String,
3073 pub version: String,
3074 pub text: String,
3075 pub messages: Vec<SavedMessage>,
3076 pub summary: String,
3077 pub slash_command_output_sections:
3078 Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3079 #[serde(default)]
3080 pub thought_process_output_sections: Vec<ThoughtProcessOutputSection<usize>>,
3081}
3082
3083impl SavedTextThread {
3084 pub const VERSION: &'static str = "0.4.0";
3085
3086 pub fn from_json(json: &str) -> Result<Self> {
3087 let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3088 match saved_context_json
3089 .get("version")
3090 .context("version not found")?
3091 {
3092 serde_json::Value::String(version) => match version.as_str() {
3093 SavedTextThread::VERSION => Ok(serde_json::from_value::<SavedTextThread>(
3094 saved_context_json,
3095 )?),
3096 SavedContextV0_3_0::VERSION => {
3097 let saved_context =
3098 serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3099 Ok(saved_context.upgrade())
3100 }
3101 SavedContextV0_2_0::VERSION => {
3102 let saved_context =
3103 serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3104 Ok(saved_context.upgrade())
3105 }
3106 SavedContextV0_1_0::VERSION => {
3107 let saved_context =
3108 serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3109 Ok(saved_context.upgrade())
3110 }
3111 _ => anyhow::bail!("unrecognized saved context version: {version:?}"),
3112 },
3113 _ => anyhow::bail!("version not found on saved context"),
3114 }
3115 }
3116
3117 fn into_ops(
3118 self,
3119 buffer: &Entity<Buffer>,
3120 cx: &mut Context<TextThread>,
3121 ) -> Vec<TextThreadOperation> {
3122 let mut operations = Vec::new();
3123 let mut version = clock::Global::new();
3124 let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3125
3126 let mut first_message_metadata = None;
3127 for message in self.messages {
3128 if message.id == MessageId(clock::Lamport::MIN) {
3129 first_message_metadata = Some(message.metadata);
3130 } else {
3131 operations.push(TextThreadOperation::InsertMessage {
3132 anchor: MessageAnchor {
3133 id: message.id,
3134 start: buffer.read(cx).anchor_before(message.start),
3135 },
3136 metadata: MessageMetadata {
3137 role: message.metadata.role,
3138 status: message.metadata.status,
3139 timestamp: message.metadata.timestamp,
3140 cache: None,
3141 },
3142 version: version.clone(),
3143 });
3144 version.observe(message.id.0);
3145 next_timestamp.observe(message.id.0);
3146 }
3147 }
3148
3149 if let Some(metadata) = first_message_metadata {
3150 let timestamp = next_timestamp.tick();
3151 operations.push(TextThreadOperation::UpdateMessage {
3152 message_id: MessageId(clock::Lamport::MIN),
3153 metadata: MessageMetadata {
3154 role: metadata.role,
3155 status: metadata.status,
3156 timestamp,
3157 cache: None,
3158 },
3159 version: version.clone(),
3160 });
3161 version.observe(timestamp);
3162 }
3163
3164 let buffer = buffer.read(cx);
3165 for section in self.slash_command_output_sections {
3166 let timestamp = next_timestamp.tick();
3167 operations.push(TextThreadOperation::SlashCommandOutputSectionAdded {
3168 timestamp,
3169 section: SlashCommandOutputSection {
3170 range: buffer.anchor_after(section.range.start)
3171 ..buffer.anchor_before(section.range.end),
3172 icon: section.icon,
3173 label: section.label,
3174 metadata: section.metadata,
3175 },
3176 version: version.clone(),
3177 });
3178
3179 version.observe(timestamp);
3180 }
3181
3182 for section in self.thought_process_output_sections {
3183 let timestamp = next_timestamp.tick();
3184 operations.push(TextThreadOperation::ThoughtProcessOutputSectionAdded {
3185 timestamp,
3186 section: ThoughtProcessOutputSection {
3187 range: buffer.anchor_after(section.range.start)
3188 ..buffer.anchor_before(section.range.end),
3189 },
3190 version: version.clone(),
3191 });
3192
3193 version.observe(timestamp);
3194 }
3195
3196 let timestamp = next_timestamp.tick();
3197 operations.push(TextThreadOperation::UpdateSummary {
3198 summary: TextThreadSummaryContent {
3199 text: self.summary,
3200 done: true,
3201 timestamp,
3202 },
3203 version: version.clone(),
3204 });
3205 version.observe(timestamp);
3206
3207 operations
3208 }
3209}
3210
3211#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3212struct SavedMessageIdPreV0_4_0(usize);
3213
3214#[derive(Serialize, Deserialize)]
3215struct SavedMessagePreV0_4_0 {
3216 id: SavedMessageIdPreV0_4_0,
3217 start: usize,
3218}
3219
3220#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3221struct SavedMessageMetadataPreV0_4_0 {
3222 role: Role,
3223 status: MessageStatus,
3224}
3225
3226#[derive(Serialize, Deserialize)]
3227struct SavedContextV0_3_0 {
3228 id: Option<TextThreadId>,
3229 zed: String,
3230 version: String,
3231 text: String,
3232 messages: Vec<SavedMessagePreV0_4_0>,
3233 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3234 summary: String,
3235 slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3236}
3237
3238impl SavedContextV0_3_0 {
3239 const VERSION: &'static str = "0.3.0";
3240
3241 fn upgrade(self) -> SavedTextThread {
3242 SavedTextThread {
3243 id: self.id,
3244 zed: self.zed,
3245 version: SavedTextThread::VERSION.into(),
3246 text: self.text,
3247 messages: self
3248 .messages
3249 .into_iter()
3250 .filter_map(|message| {
3251 let metadata = self.message_metadata.get(&message.id)?;
3252 let timestamp = clock::Lamport {
3253 replica_id: ReplicaId::default(),
3254 value: message.id.0 as u32,
3255 };
3256 Some(SavedMessage {
3257 id: MessageId(timestamp),
3258 start: message.start,
3259 metadata: MessageMetadata {
3260 role: metadata.role,
3261 status: metadata.status.clone(),
3262 timestamp,
3263 cache: None,
3264 },
3265 })
3266 })
3267 .collect(),
3268 summary: self.summary,
3269 slash_command_output_sections: self.slash_command_output_sections,
3270 thought_process_output_sections: Vec::new(),
3271 }
3272 }
3273}
3274
3275#[derive(Serialize, Deserialize)]
3276struct SavedContextV0_2_0 {
3277 id: Option<TextThreadId>,
3278 zed: String,
3279 version: String,
3280 text: String,
3281 messages: Vec<SavedMessagePreV0_4_0>,
3282 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3283 summary: String,
3284}
3285
3286impl SavedContextV0_2_0 {
3287 const VERSION: &'static str = "0.2.0";
3288
3289 fn upgrade(self) -> SavedTextThread {
3290 SavedContextV0_3_0 {
3291 id: self.id,
3292 zed: self.zed,
3293 version: SavedContextV0_3_0::VERSION.to_string(),
3294 text: self.text,
3295 messages: self.messages,
3296 message_metadata: self.message_metadata,
3297 summary: self.summary,
3298 slash_command_output_sections: Vec::new(),
3299 }
3300 .upgrade()
3301 }
3302}
3303
3304#[derive(Serialize, Deserialize)]
3305struct SavedContextV0_1_0 {
3306 id: Option<TextThreadId>,
3307 zed: String,
3308 version: String,
3309 text: String,
3310 messages: Vec<SavedMessagePreV0_4_0>,
3311 message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3312 summary: String,
3313 api_url: Option<String>,
3314 model: OpenAiModel,
3315}
3316
3317impl SavedContextV0_1_0 {
3318 const VERSION: &'static str = "0.1.0";
3319
3320 fn upgrade(self) -> SavedTextThread {
3321 SavedContextV0_2_0 {
3322 id: self.id,
3323 zed: self.zed,
3324 version: SavedContextV0_2_0::VERSION.to_string(),
3325 text: self.text,
3326 messages: self.messages,
3327 message_metadata: self.message_metadata,
3328 summary: self.summary,
3329 }
3330 .upgrade()
3331 }
3332}
3333
3334#[derive(Debug, Clone)]
3335pub struct SavedTextThreadMetadata {
3336 pub title: SharedString,
3337 pub path: Arc<Path>,
3338 pub mtime: chrono::DateTime<chrono::Local>,
3339}