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