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