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