text_thread.rs

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