context.rs

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