context.rs

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