context.rs

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