context.rs

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