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