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_executor().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        self.pending_token_count = cx.spawn(|this, mut cx| {
1194            async move {
1195                cx.background_executor()
1196                    .timer(Duration::from_millis(200))
1197                    .await;
1198
1199                let token_count = cx.update(|cx| model.count_tokens(request, cx))?.await?;
1200                this.update(&mut cx, |this, cx| {
1201                    this.token_count = Some(token_count);
1202                    this.start_cache_warming(&model, cx);
1203                    cx.notify()
1204                })
1205            }
1206            .log_err()
1207        });
1208    }
1209
1210    pub fn mark_cache_anchors(
1211        &mut self,
1212        cache_configuration: &Option<LanguageModelCacheConfiguration>,
1213        speculative: bool,
1214        cx: &mut Context<Self>,
1215    ) -> bool {
1216        let cache_configuration =
1217            cache_configuration
1218                .as_ref()
1219                .unwrap_or(&LanguageModelCacheConfiguration {
1220                    max_cache_anchors: 0,
1221                    should_speculate: false,
1222                    min_total_token: 0,
1223                });
1224
1225        let messages: Vec<Message> = self.messages(cx).collect();
1226
1227        let mut sorted_messages = messages.clone();
1228        if speculative {
1229            // Avoid caching the last message if this is a speculative cache fetch as
1230            // it's likely to change.
1231            sorted_messages.pop();
1232        }
1233        sorted_messages.retain(|m| m.role == Role::User);
1234        sorted_messages.sort_by(|a, b| b.offset_range.len().cmp(&a.offset_range.len()));
1235
1236        let cache_anchors = if self.token_count.unwrap_or(0) < cache_configuration.min_total_token {
1237            // If we have't hit the minimum threshold to enable caching, don't cache anything.
1238            0
1239        } else {
1240            // Save 1 anchor for the inline assistant to use.
1241            max(cache_configuration.max_cache_anchors, 1) - 1
1242        };
1243        sorted_messages.truncate(cache_anchors);
1244
1245        let anchors: HashSet<MessageId> = sorted_messages
1246            .into_iter()
1247            .map(|message| message.id)
1248            .collect();
1249
1250        let buffer = self.buffer.read(cx).snapshot();
1251        let invalidated_caches: HashSet<MessageId> = messages
1252            .iter()
1253            .scan(false, |encountered_invalid, message| {
1254                let message_id = message.id;
1255                let is_invalid = self
1256                    .messages_metadata
1257                    .get(&message_id)
1258                    .map_or(true, |metadata| {
1259                        !metadata.is_cache_valid(&buffer, &message.offset_range)
1260                            || *encountered_invalid
1261                    });
1262                *encountered_invalid |= is_invalid;
1263                Some(if is_invalid { Some(message_id) } else { None })
1264            })
1265            .flatten()
1266            .collect();
1267
1268        let last_anchor = messages.iter().rev().find_map(|message| {
1269            if anchors.contains(&message.id) {
1270                Some(message.id)
1271            } else {
1272                None
1273            }
1274        });
1275
1276        let mut new_anchor_needs_caching = false;
1277        let current_version = &buffer.version;
1278        // If we have no anchors, mark all messages as not being cached.
1279        let mut hit_last_anchor = last_anchor.is_none();
1280
1281        for message in messages.iter() {
1282            if hit_last_anchor {
1283                self.update_metadata(message.id, cx, |metadata| metadata.cache = None);
1284                continue;
1285            }
1286
1287            if let Some(last_anchor) = last_anchor {
1288                if message.id == last_anchor {
1289                    hit_last_anchor = true;
1290                }
1291            }
1292
1293            new_anchor_needs_caching = new_anchor_needs_caching
1294                || (invalidated_caches.contains(&message.id) && anchors.contains(&message.id));
1295
1296            self.update_metadata(message.id, cx, |metadata| {
1297                let cache_status = if invalidated_caches.contains(&message.id) {
1298                    CacheStatus::Pending
1299                } else {
1300                    metadata
1301                        .cache
1302                        .as_ref()
1303                        .map_or(CacheStatus::Pending, |cm| cm.status.clone())
1304                };
1305                metadata.cache = Some(MessageCacheMetadata {
1306                    is_anchor: anchors.contains(&message.id),
1307                    is_final_anchor: hit_last_anchor,
1308                    status: cache_status,
1309                    cached_at: current_version.clone(),
1310                });
1311            });
1312        }
1313        new_anchor_needs_caching
1314    }
1315
1316    fn start_cache_warming(&mut self, model: &Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1317        let cache_configuration = model.cache_configuration();
1318
1319        if !self.mark_cache_anchors(&cache_configuration, true, cx) {
1320            return;
1321        }
1322        if !self.pending_completions.is_empty() {
1323            return;
1324        }
1325        if let Some(cache_configuration) = cache_configuration {
1326            if !cache_configuration.should_speculate {
1327                return;
1328            }
1329        }
1330
1331        let request = {
1332            let mut req = self.to_completion_request(RequestType::Chat, cx);
1333            // Skip the last message because it's likely to change and
1334            // therefore would be a waste to cache.
1335            req.messages.pop();
1336            req.messages.push(LanguageModelRequestMessage {
1337                role: Role::User,
1338                content: vec!["Respond only with OK, nothing else.".into()],
1339                cache: false,
1340            });
1341            req
1342        };
1343
1344        let model = Arc::clone(model);
1345        self.pending_cache_warming_task = cx.spawn(|this, mut cx| {
1346            async move {
1347                match model.stream_completion(request, &cx).await {
1348                    Ok(mut stream) => {
1349                        stream.next().await;
1350                        log::info!("Cache warming completed successfully");
1351                    }
1352                    Err(e) => {
1353                        log::warn!("Cache warming failed: {}", e);
1354                    }
1355                };
1356                this.update(&mut cx, |this, cx| {
1357                    this.update_cache_status_for_completion(cx);
1358                })
1359                .ok();
1360                anyhow::Ok(())
1361            }
1362            .log_err()
1363        });
1364    }
1365
1366    pub fn update_cache_status_for_completion(&mut self, cx: &mut Context<Self>) {
1367        let cached_message_ids: Vec<MessageId> = self
1368            .messages_metadata
1369            .iter()
1370            .filter_map(|(message_id, metadata)| {
1371                metadata.cache.as_ref().and_then(|cache| {
1372                    if cache.status == CacheStatus::Pending {
1373                        Some(*message_id)
1374                    } else {
1375                        None
1376                    }
1377                })
1378            })
1379            .collect();
1380
1381        for message_id in cached_message_ids {
1382            self.update_metadata(message_id, cx, |metadata| {
1383                if let Some(cache) = &mut metadata.cache {
1384                    cache.status = CacheStatus::Cached;
1385                }
1386            });
1387        }
1388        cx.notify();
1389    }
1390
1391    pub fn reparse(&mut self, cx: &mut Context<Self>) {
1392        let buffer = self.buffer.read(cx).text_snapshot();
1393        let mut row_ranges = self
1394            .edits_since_last_parse
1395            .consume()
1396            .into_iter()
1397            .map(|edit| {
1398                let start_row = buffer.offset_to_point(edit.new.start).row;
1399                let end_row = buffer.offset_to_point(edit.new.end).row + 1;
1400                start_row..end_row
1401            })
1402            .peekable();
1403
1404        let mut removed_parsed_slash_command_ranges = Vec::new();
1405        let mut updated_parsed_slash_commands = Vec::new();
1406        let mut removed_patches = Vec::new();
1407        let mut updated_patches = Vec::new();
1408        while let Some(mut row_range) = row_ranges.next() {
1409            while let Some(next_row_range) = row_ranges.peek() {
1410                if row_range.end >= next_row_range.start {
1411                    row_range.end = next_row_range.end;
1412                    row_ranges.next();
1413                } else {
1414                    break;
1415                }
1416            }
1417
1418            let start = buffer.anchor_before(Point::new(row_range.start, 0));
1419            let end = buffer.anchor_after(Point::new(
1420                row_range.end - 1,
1421                buffer.line_len(row_range.end - 1),
1422            ));
1423
1424            self.reparse_slash_commands_in_range(
1425                start..end,
1426                &buffer,
1427                &mut updated_parsed_slash_commands,
1428                &mut removed_parsed_slash_command_ranges,
1429                cx,
1430            );
1431            self.invalidate_pending_slash_commands(&buffer, cx);
1432            self.reparse_patches_in_range(
1433                start..end,
1434                &buffer,
1435                &mut updated_patches,
1436                &mut removed_patches,
1437                cx,
1438            );
1439        }
1440
1441        if !updated_parsed_slash_commands.is_empty()
1442            || !removed_parsed_slash_command_ranges.is_empty()
1443        {
1444            cx.emit(ContextEvent::ParsedSlashCommandsUpdated {
1445                removed: removed_parsed_slash_command_ranges,
1446                updated: updated_parsed_slash_commands,
1447            });
1448        }
1449
1450        if !updated_patches.is_empty() || !removed_patches.is_empty() {
1451            cx.emit(ContextEvent::PatchesUpdated {
1452                removed: removed_patches,
1453                updated: updated_patches,
1454            });
1455        }
1456    }
1457
1458    fn reparse_slash_commands_in_range(
1459        &mut self,
1460        range: Range<text::Anchor>,
1461        buffer: &BufferSnapshot,
1462        updated: &mut Vec<ParsedSlashCommand>,
1463        removed: &mut Vec<Range<text::Anchor>>,
1464        cx: &App,
1465    ) {
1466        let old_range = self.pending_command_indices_for_range(range.clone(), cx);
1467
1468        let mut new_commands = Vec::new();
1469        let mut lines = buffer.text_for_range(range).lines();
1470        let mut offset = lines.offset();
1471        while let Some(line) = lines.next() {
1472            if let Some(command_line) = SlashCommandLine::parse(line) {
1473                let name = &line[command_line.name.clone()];
1474                let arguments = command_line
1475                    .arguments
1476                    .iter()
1477                    .filter_map(|argument_range| {
1478                        if argument_range.is_empty() {
1479                            None
1480                        } else {
1481                            line.get(argument_range.clone())
1482                        }
1483                    })
1484                    .map(ToOwned::to_owned)
1485                    .collect::<SmallVec<_>>();
1486                if let Some(command) = self.slash_commands.command(name, cx) {
1487                    if !command.requires_argument() || !arguments.is_empty() {
1488                        let start_ix = offset + command_line.name.start - 1;
1489                        let end_ix = offset
1490                            + command_line
1491                                .arguments
1492                                .last()
1493                                .map_or(command_line.name.end, |argument| argument.end);
1494                        let source_range =
1495                            buffer.anchor_after(start_ix)..buffer.anchor_after(end_ix);
1496                        let pending_command = ParsedSlashCommand {
1497                            name: name.to_string(),
1498                            arguments,
1499                            source_range,
1500                            status: PendingSlashCommandStatus::Idle,
1501                        };
1502                        updated.push(pending_command.clone());
1503                        new_commands.push(pending_command);
1504                    }
1505                }
1506            }
1507
1508            offset = lines.offset();
1509        }
1510
1511        let removed_commands = self.parsed_slash_commands.splice(old_range, new_commands);
1512        removed.extend(removed_commands.map(|command| command.source_range));
1513    }
1514
1515    fn invalidate_pending_slash_commands(
1516        &mut self,
1517        buffer: &BufferSnapshot,
1518        cx: &mut Context<Self>,
1519    ) {
1520        let mut invalidated_command_ids = Vec::new();
1521        for (&command_id, command) in self.invoked_slash_commands.iter_mut() {
1522            if !matches!(command.status, InvokedSlashCommandStatus::Finished)
1523                && (!command.range.start.is_valid(buffer) || !command.range.end.is_valid(buffer))
1524            {
1525                command.status = InvokedSlashCommandStatus::Finished;
1526                cx.emit(ContextEvent::InvokedSlashCommandChanged { command_id });
1527                invalidated_command_ids.push(command_id);
1528            }
1529        }
1530
1531        for command_id in invalidated_command_ids {
1532            let version = self.version.clone();
1533            let timestamp = self.next_timestamp();
1534            self.push_op(
1535                ContextOperation::SlashCommandFinished {
1536                    id: command_id,
1537                    timestamp,
1538                    error_message: None,
1539                    version: version.clone(),
1540                },
1541                cx,
1542            );
1543        }
1544    }
1545
1546    fn reparse_patches_in_range(
1547        &mut self,
1548        range: Range<text::Anchor>,
1549        buffer: &BufferSnapshot,
1550        updated: &mut Vec<Range<text::Anchor>>,
1551        removed: &mut Vec<Range<text::Anchor>>,
1552        cx: &mut Context<Self>,
1553    ) {
1554        // Rebuild the XML tags in the edited range.
1555        let intersecting_tags_range =
1556            self.indices_intersecting_buffer_range(&self.xml_tags, range.clone(), cx);
1557        let new_tags = self.parse_xml_tags_in_range(buffer, range.clone(), cx);
1558        self.xml_tags
1559            .splice(intersecting_tags_range.clone(), new_tags);
1560
1561        // Find which patches intersect the changed range.
1562        let intersecting_patches_range =
1563            self.indices_intersecting_buffer_range(&self.patches, range.clone(), cx);
1564
1565        // Reparse all tags after the last unchanged patch before the change.
1566        let mut tags_start_ix = 0;
1567        if let Some(preceding_unchanged_patch) =
1568            self.patches[..intersecting_patches_range.start].last()
1569        {
1570            tags_start_ix = match self.xml_tags.binary_search_by(|tag| {
1571                tag.range
1572                    .start
1573                    .cmp(&preceding_unchanged_patch.range.end, buffer)
1574                    .then(Ordering::Less)
1575            }) {
1576                Ok(ix) | Err(ix) => ix,
1577            };
1578        }
1579
1580        // Rebuild the patches in the range.
1581        let new_patches = self.parse_patches(tags_start_ix, range.end, buffer, cx);
1582        updated.extend(new_patches.iter().map(|patch| patch.range.clone()));
1583        let removed_patches = self.patches.splice(intersecting_patches_range, new_patches);
1584        removed.extend(
1585            removed_patches
1586                .map(|patch| patch.range)
1587                .filter(|range| !updated.contains(&range)),
1588        );
1589    }
1590
1591    fn parse_xml_tags_in_range(
1592        &self,
1593        buffer: &BufferSnapshot,
1594        range: Range<text::Anchor>,
1595        cx: &App,
1596    ) -> Vec<XmlTag> {
1597        let mut messages = self.messages(cx).peekable();
1598
1599        let mut tags = Vec::new();
1600        let mut lines = buffer.text_for_range(range).lines();
1601        let mut offset = lines.offset();
1602
1603        while let Some(line) = lines.next() {
1604            while let Some(message) = messages.peek() {
1605                if offset < message.offset_range.end {
1606                    break;
1607                } else {
1608                    messages.next();
1609                }
1610            }
1611
1612            let is_assistant_message = messages
1613                .peek()
1614                .map_or(false, |message| message.role == Role::Assistant);
1615            if is_assistant_message {
1616                for (start_ix, _) in line.match_indices('<') {
1617                    let mut name_start_ix = start_ix + 1;
1618                    let closing_bracket_ix = line[start_ix..].find('>').map(|i| start_ix + i);
1619                    if let Some(closing_bracket_ix) = closing_bracket_ix {
1620                        let end_ix = closing_bracket_ix + 1;
1621                        let mut is_open_tag = true;
1622                        if line[name_start_ix..closing_bracket_ix].starts_with('/') {
1623                            name_start_ix += 1;
1624                            is_open_tag = false;
1625                        }
1626                        let tag_inner = &line[name_start_ix..closing_bracket_ix];
1627                        let tag_name_len = tag_inner
1628                            .find(|c: char| c.is_whitespace())
1629                            .unwrap_or(tag_inner.len());
1630                        if let Ok(kind) = XmlTagKind::from_str(&tag_inner[..tag_name_len]) {
1631                            tags.push(XmlTag {
1632                                range: buffer.anchor_after(offset + start_ix)
1633                                    ..buffer.anchor_before(offset + end_ix),
1634                                is_open_tag,
1635                                kind,
1636                            });
1637                        };
1638                    }
1639                }
1640            }
1641
1642            offset = lines.offset();
1643        }
1644        tags
1645    }
1646
1647    fn parse_patches(
1648        &mut self,
1649        tags_start_ix: usize,
1650        buffer_end: text::Anchor,
1651        buffer: &BufferSnapshot,
1652        cx: &App,
1653    ) -> Vec<AssistantPatch> {
1654        let mut new_patches = Vec::new();
1655        let mut pending_patch = None;
1656        let mut patch_tag_depth = 0;
1657        let mut tags = self.xml_tags[tags_start_ix..].iter().peekable();
1658        'tags: while let Some(tag) = tags.next() {
1659            if tag.range.start.cmp(&buffer_end, buffer).is_gt() && patch_tag_depth == 0 {
1660                break;
1661            }
1662
1663            if tag.kind == XmlTagKind::Patch && tag.is_open_tag {
1664                patch_tag_depth += 1;
1665                let patch_start = tag.range.start;
1666                let mut edits = Vec::<Result<AssistantEdit>>::new();
1667                let mut patch = AssistantPatch {
1668                    range: patch_start..patch_start,
1669                    title: String::new().into(),
1670                    edits: Default::default(),
1671                    status: crate::AssistantPatchStatus::Pending,
1672                };
1673
1674                while let Some(tag) = tags.next() {
1675                    if tag.kind == XmlTagKind::Patch && !tag.is_open_tag {
1676                        patch_tag_depth -= 1;
1677                        if patch_tag_depth == 0 {
1678                            patch.range.end = tag.range.end;
1679
1680                            // Include the line immediately after this <patch> tag if it's empty.
1681                            let patch_end_offset = patch.range.end.to_offset(buffer);
1682                            let mut patch_end_chars = buffer.chars_at(patch_end_offset);
1683                            if patch_end_chars.next() == Some('\n')
1684                                && patch_end_chars.next().map_or(true, |ch| ch == '\n')
1685                            {
1686                                let messages = self.messages_for_offsets(
1687                                    [patch_end_offset, patch_end_offset + 1],
1688                                    cx,
1689                                );
1690                                if messages.len() == 1 {
1691                                    patch.range.end = buffer.anchor_before(patch_end_offset + 1);
1692                                }
1693                            }
1694
1695                            edits.sort_unstable_by(|a, b| {
1696                                if let (Ok(a), Ok(b)) = (a, b) {
1697                                    a.path.cmp(&b.path)
1698                                } else {
1699                                    Ordering::Equal
1700                                }
1701                            });
1702                            patch.edits = edits.into();
1703                            patch.status = AssistantPatchStatus::Ready;
1704                            new_patches.push(patch);
1705                            continue 'tags;
1706                        }
1707                    }
1708
1709                    if tag.kind == XmlTagKind::Title && tag.is_open_tag {
1710                        let content_start = tag.range.end;
1711                        while let Some(tag) = tags.next() {
1712                            if tag.kind == XmlTagKind::Title && !tag.is_open_tag {
1713                                let content_end = tag.range.start;
1714                                patch.title =
1715                                    trimmed_text_in_range(buffer, content_start..content_end)
1716                                        .into();
1717                                break;
1718                            }
1719                        }
1720                    }
1721
1722                    if tag.kind == XmlTagKind::Edit && tag.is_open_tag {
1723                        let mut path = None;
1724                        let mut old_text = None;
1725                        let mut new_text = None;
1726                        let mut operation = None;
1727                        let mut description = None;
1728
1729                        while let Some(tag) = tags.next() {
1730                            if tag.kind == XmlTagKind::Edit && !tag.is_open_tag {
1731                                edits.push(AssistantEdit::new(
1732                                    path,
1733                                    operation,
1734                                    old_text,
1735                                    new_text,
1736                                    description,
1737                                ));
1738                                break;
1739                            }
1740
1741                            if tag.is_open_tag
1742                                && [
1743                                    XmlTagKind::Path,
1744                                    XmlTagKind::OldText,
1745                                    XmlTagKind::NewText,
1746                                    XmlTagKind::Operation,
1747                                    XmlTagKind::Description,
1748                                ]
1749                                .contains(&tag.kind)
1750                            {
1751                                let kind = tag.kind;
1752                                let content_start = tag.range.end;
1753                                if let Some(tag) = tags.peek() {
1754                                    if tag.kind == kind && !tag.is_open_tag {
1755                                        let tag = tags.next().unwrap();
1756                                        let content_end = tag.range.start;
1757                                        let content = trimmed_text_in_range(
1758                                            buffer,
1759                                            content_start..content_end,
1760                                        );
1761                                        match kind {
1762                                            XmlTagKind::Path => path = Some(content),
1763                                            XmlTagKind::Operation => operation = Some(content),
1764                                            XmlTagKind::OldText => {
1765                                                old_text = Some(content).filter(|s| !s.is_empty())
1766                                            }
1767                                            XmlTagKind::NewText => {
1768                                                new_text = Some(content).filter(|s| !s.is_empty())
1769                                            }
1770                                            XmlTagKind::Description => {
1771                                                description =
1772                                                    Some(content).filter(|s| !s.is_empty())
1773                                            }
1774                                            _ => {}
1775                                        }
1776                                    }
1777                                }
1778                            }
1779                        }
1780                    }
1781                }
1782
1783                patch.edits = edits.into();
1784                pending_patch = Some(patch);
1785            }
1786        }
1787
1788        if let Some(mut pending_patch) = pending_patch {
1789            let patch_start = pending_patch.range.start.to_offset(buffer);
1790            if let Some(message) = self.message_for_offset(patch_start, cx) {
1791                if message.anchor_range.end == text::Anchor::MAX {
1792                    pending_patch.range.end = text::Anchor::MAX;
1793                } else {
1794                    let message_end = buffer.anchor_after(message.offset_range.end - 1);
1795                    pending_patch.range.end = message_end;
1796                }
1797            } else {
1798                pending_patch.range.end = text::Anchor::MAX;
1799            }
1800
1801            new_patches.push(pending_patch);
1802        }
1803
1804        new_patches
1805    }
1806
1807    pub fn pending_command_for_position(
1808        &mut self,
1809        position: language::Anchor,
1810        cx: &mut Context<Self>,
1811    ) -> Option<&mut ParsedSlashCommand> {
1812        let buffer = self.buffer.read(cx);
1813        match self
1814            .parsed_slash_commands
1815            .binary_search_by(|probe| probe.source_range.end.cmp(&position, buffer))
1816        {
1817            Ok(ix) => Some(&mut self.parsed_slash_commands[ix]),
1818            Err(ix) => {
1819                let cmd = self.parsed_slash_commands.get_mut(ix)?;
1820                if position.cmp(&cmd.source_range.start, buffer).is_ge()
1821                    && position.cmp(&cmd.source_range.end, buffer).is_le()
1822                {
1823                    Some(cmd)
1824                } else {
1825                    None
1826                }
1827            }
1828        }
1829    }
1830
1831    pub fn pending_commands_for_range(
1832        &self,
1833        range: Range<language::Anchor>,
1834        cx: &App,
1835    ) -> &[ParsedSlashCommand] {
1836        let range = self.pending_command_indices_for_range(range, cx);
1837        &self.parsed_slash_commands[range]
1838    }
1839
1840    fn pending_command_indices_for_range(
1841        &self,
1842        range: Range<language::Anchor>,
1843        cx: &App,
1844    ) -> Range<usize> {
1845        self.indices_intersecting_buffer_range(&self.parsed_slash_commands, range, cx)
1846    }
1847
1848    fn indices_intersecting_buffer_range<T: ContextAnnotation>(
1849        &self,
1850        all_annotations: &[T],
1851        range: Range<language::Anchor>,
1852        cx: &App,
1853    ) -> Range<usize> {
1854        let buffer = self.buffer.read(cx);
1855        let start_ix = match all_annotations
1856            .binary_search_by(|probe| probe.range().end.cmp(&range.start, &buffer))
1857        {
1858            Ok(ix) | Err(ix) => ix,
1859        };
1860        let end_ix = match all_annotations
1861            .binary_search_by(|probe| probe.range().start.cmp(&range.end, &buffer))
1862        {
1863            Ok(ix) => ix + 1,
1864            Err(ix) => ix,
1865        };
1866        start_ix..end_ix
1867    }
1868
1869    pub fn insert_command_output(
1870        &mut self,
1871        command_source_range: Range<language::Anchor>,
1872        name: &str,
1873        output: Task<SlashCommandResult>,
1874        ensure_trailing_newline: bool,
1875        cx: &mut Context<Self>,
1876    ) {
1877        let version = self.version.clone();
1878        let command_id = InvokedSlashCommandId(self.next_timestamp());
1879
1880        const PENDING_OUTPUT_END_MARKER: &str = "";
1881
1882        let (command_range, command_source_range, insert_position, first_transaction) =
1883            self.buffer.update(cx, |buffer, cx| {
1884                let command_source_range = command_source_range.to_offset(buffer);
1885                let mut insertion = format!("\n{PENDING_OUTPUT_END_MARKER}");
1886                if ensure_trailing_newline {
1887                    insertion.push('\n');
1888                }
1889
1890                buffer.finalize_last_transaction();
1891                buffer.start_transaction();
1892                buffer.edit(
1893                    [(
1894                        command_source_range.end..command_source_range.end,
1895                        insertion,
1896                    )],
1897                    None,
1898                    cx,
1899                );
1900                let first_transaction = buffer.end_transaction(cx).unwrap();
1901                buffer.finalize_last_transaction();
1902
1903                let insert_position = buffer.anchor_after(command_source_range.end + 1);
1904                let command_range = buffer.anchor_after(command_source_range.start)
1905                    ..buffer.anchor_before(
1906                        command_source_range.end + 1 + PENDING_OUTPUT_END_MARKER.len(),
1907                    );
1908                let command_source_range = buffer.anchor_before(command_source_range.start)
1909                    ..buffer.anchor_before(command_source_range.end + 1);
1910                (
1911                    command_range,
1912                    command_source_range,
1913                    insert_position,
1914                    first_transaction,
1915                )
1916            });
1917        self.reparse(cx);
1918
1919        let insert_output_task = cx.spawn(|this, mut cx| async move {
1920            let run_command = async {
1921                let mut stream = output.await?;
1922
1923                struct PendingSection {
1924                    start: language::Anchor,
1925                    icon: IconName,
1926                    label: SharedString,
1927                    metadata: Option<serde_json::Value>,
1928                }
1929
1930                let mut pending_section_stack: Vec<PendingSection> = Vec::new();
1931                let mut last_role: Option<Role> = None;
1932                let mut last_section_range = None;
1933
1934                while let Some(event) = stream.next().await {
1935                    let event = event?;
1936                    this.update(&mut cx, |this, cx| {
1937                        this.buffer.update(cx, |buffer, _cx| {
1938                            buffer.finalize_last_transaction();
1939                            buffer.start_transaction()
1940                        });
1941
1942                        match event {
1943                            SlashCommandEvent::StartMessage {
1944                                role,
1945                                merge_same_roles,
1946                            } => {
1947                                if !merge_same_roles && Some(role) != last_role {
1948                                    let offset = this.buffer.read_with(cx, |buffer, _cx| {
1949                                        insert_position.to_offset(buffer)
1950                                    });
1951                                    this.insert_message_at_offset(
1952                                        offset,
1953                                        role,
1954                                        MessageStatus::Pending,
1955                                        cx,
1956                                    );
1957                                }
1958
1959                                last_role = Some(role);
1960                            }
1961                            SlashCommandEvent::StartSection {
1962                                icon,
1963                                label,
1964                                metadata,
1965                            } => {
1966                                this.buffer.update(cx, |buffer, cx| {
1967                                    let insert_point = insert_position.to_point(buffer);
1968                                    if insert_point.column > 0 {
1969                                        buffer.edit([(insert_point..insert_point, "\n")], None, cx);
1970                                    }
1971
1972                                    pending_section_stack.push(PendingSection {
1973                                        start: buffer.anchor_before(insert_position),
1974                                        icon,
1975                                        label,
1976                                        metadata,
1977                                    });
1978                                });
1979                            }
1980                            SlashCommandEvent::Content(SlashCommandContent::Text {
1981                                text,
1982                                run_commands_in_text,
1983                            }) => {
1984                                let start = this.buffer.read(cx).anchor_before(insert_position);
1985
1986                                this.buffer.update(cx, |buffer, cx| {
1987                                    buffer.edit(
1988                                        [(insert_position..insert_position, text)],
1989                                        None,
1990                                        cx,
1991                                    )
1992                                });
1993
1994                                let end = this.buffer.read(cx).anchor_before(insert_position);
1995                                if run_commands_in_text {
1996                                    if let Some(invoked_slash_command) =
1997                                        this.invoked_slash_commands.get_mut(&command_id)
1998                                    {
1999                                        invoked_slash_command
2000                                            .run_commands_in_ranges
2001                                            .push(start..end);
2002                                    }
2003                                }
2004                            }
2005                            SlashCommandEvent::EndSection => {
2006                                if let Some(pending_section) = pending_section_stack.pop() {
2007                                    let offset_range = (pending_section.start..insert_position)
2008                                        .to_offset(this.buffer.read(cx));
2009                                    if !offset_range.is_empty() {
2010                                        let range = this.buffer.update(cx, |buffer, _cx| {
2011                                            buffer.anchor_after(offset_range.start)
2012                                                ..buffer.anchor_before(offset_range.end)
2013                                        });
2014                                        this.insert_slash_command_output_section(
2015                                            SlashCommandOutputSection {
2016                                                range: range.clone(),
2017                                                icon: pending_section.icon,
2018                                                label: pending_section.label,
2019                                                metadata: pending_section.metadata,
2020                                            },
2021                                            cx,
2022                                        );
2023                                        last_section_range = Some(range);
2024                                    }
2025                                }
2026                            }
2027                        }
2028
2029                        this.buffer.update(cx, |buffer, cx| {
2030                            if let Some(event_transaction) = buffer.end_transaction(cx) {
2031                                buffer.merge_transactions(event_transaction, first_transaction);
2032                            }
2033                        });
2034                    })?;
2035                }
2036
2037                this.update(&mut cx, |this, cx| {
2038                    this.buffer.update(cx, |buffer, cx| {
2039                        buffer.finalize_last_transaction();
2040                        buffer.start_transaction();
2041
2042                        let mut deletions = vec![(command_source_range.to_offset(buffer), "")];
2043                        let insert_position = insert_position.to_offset(buffer);
2044                        let command_range_end = command_range.end.to_offset(buffer);
2045
2046                        if buffer.contains_str_at(insert_position, PENDING_OUTPUT_END_MARKER) {
2047                            deletions.push((
2048                                insert_position..insert_position + PENDING_OUTPUT_END_MARKER.len(),
2049                                "",
2050                            ));
2051                        }
2052
2053                        if ensure_trailing_newline
2054                            && buffer.contains_str_at(command_range_end, "\n")
2055                        {
2056                            let newline_offset = insert_position.saturating_sub(1);
2057                            if buffer.contains_str_at(newline_offset, "\n")
2058                                && last_section_range.map_or(true, |last_section_range| {
2059                                    !last_section_range
2060                                        .to_offset(buffer)
2061                                        .contains(&newline_offset)
2062                                })
2063                            {
2064                                deletions.push((command_range_end..command_range_end + 1, ""));
2065                            }
2066                        }
2067
2068                        buffer.edit(deletions, None, cx);
2069
2070                        if let Some(deletion_transaction) = buffer.end_transaction(cx) {
2071                            buffer.merge_transactions(deletion_transaction, first_transaction);
2072                        }
2073                    });
2074                })?;
2075
2076                debug_assert!(pending_section_stack.is_empty());
2077
2078                anyhow::Ok(())
2079            };
2080
2081            let command_result = run_command.await;
2082
2083            this.update(&mut cx, |this, cx| {
2084                let version = this.version.clone();
2085                let timestamp = this.next_timestamp();
2086                let Some(invoked_slash_command) = this.invoked_slash_commands.get_mut(&command_id)
2087                else {
2088                    return;
2089                };
2090                let mut error_message = None;
2091                match command_result {
2092                    Ok(()) => {
2093                        invoked_slash_command.status = InvokedSlashCommandStatus::Finished;
2094                    }
2095                    Err(error) => {
2096                        let message = error.to_string();
2097                        invoked_slash_command.status =
2098                            InvokedSlashCommandStatus::Error(message.clone().into());
2099                        error_message = Some(message);
2100                    }
2101                }
2102
2103                cx.emit(ContextEvent::InvokedSlashCommandChanged { command_id });
2104                this.push_op(
2105                    ContextOperation::SlashCommandFinished {
2106                        id: command_id,
2107                        timestamp,
2108                        error_message,
2109                        version,
2110                    },
2111                    cx,
2112                );
2113            })
2114            .ok();
2115        });
2116
2117        self.invoked_slash_commands.insert(
2118            command_id,
2119            InvokedSlashCommand {
2120                name: name.to_string().into(),
2121                range: command_range.clone(),
2122                run_commands_in_ranges: Vec::new(),
2123                status: InvokedSlashCommandStatus::Running(insert_output_task),
2124                transaction: Some(first_transaction),
2125                timestamp: command_id.0,
2126            },
2127        );
2128        cx.emit(ContextEvent::InvokedSlashCommandChanged { command_id });
2129        self.push_op(
2130            ContextOperation::SlashCommandStarted {
2131                id: command_id,
2132                output_range: command_range,
2133                name: name.to_string(),
2134                version,
2135            },
2136            cx,
2137        );
2138    }
2139
2140    fn insert_slash_command_output_section(
2141        &mut self,
2142        section: SlashCommandOutputSection<language::Anchor>,
2143        cx: &mut Context<Self>,
2144    ) {
2145        let buffer = self.buffer.read(cx);
2146        let insertion_ix = match self
2147            .slash_command_output_sections
2148            .binary_search_by(|probe| probe.range.cmp(&section.range, buffer))
2149        {
2150            Ok(ix) | Err(ix) => ix,
2151        };
2152        self.slash_command_output_sections
2153            .insert(insertion_ix, section.clone());
2154        cx.emit(ContextEvent::SlashCommandOutputSectionAdded {
2155            section: section.clone(),
2156        });
2157        let version = self.version.clone();
2158        let timestamp = self.next_timestamp();
2159        self.push_op(
2160            ContextOperation::SlashCommandOutputSectionAdded {
2161                timestamp,
2162                section,
2163                version,
2164            },
2165            cx,
2166        );
2167    }
2168
2169    pub fn completion_provider_changed(&mut self, cx: &mut Context<Self>) {
2170        self.count_remaining_tokens(cx);
2171    }
2172
2173    fn get_last_valid_message_id(&self, cx: &Context<Self>) -> Option<MessageId> {
2174        self.message_anchors.iter().rev().find_map(|message| {
2175            message
2176                .start
2177                .is_valid(self.buffer.read(cx))
2178                .then_some(message.id)
2179        })
2180    }
2181
2182    pub fn assist(
2183        &mut self,
2184        request_type: RequestType,
2185        cx: &mut Context<Self>,
2186    ) -> Option<MessageAnchor> {
2187        let model_registry = LanguageModelRegistry::read_global(cx);
2188        let provider = model_registry.active_provider()?;
2189        let model = model_registry.active_model()?;
2190        let last_message_id = self.get_last_valid_message_id(cx)?;
2191
2192        if !provider.is_authenticated(cx) {
2193            log::info!("completion provider has no credentials");
2194            return None;
2195        }
2196        // Compute which messages to cache, including the last one.
2197        self.mark_cache_anchors(&model.cache_configuration(), false, cx);
2198
2199        let request = self.to_completion_request(request_type, cx);
2200
2201        let assistant_message = self
2202            .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
2203            .unwrap();
2204
2205        // Queue up the user's next reply.
2206        let user_message = self
2207            .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
2208            .unwrap();
2209
2210        let pending_completion_id = post_inc(&mut self.completion_count);
2211
2212        let task = cx.spawn({
2213            |this, mut cx| async move {
2214                let stream = model.stream_completion(request, &cx);
2215                let assistant_message_id = assistant_message.id;
2216                let mut response_latency = None;
2217                let stream_completion = async {
2218                    let request_start = Instant::now();
2219                    let mut events = stream.await?;
2220                    let mut stop_reason = StopReason::EndTurn;
2221
2222                    while let Some(event) = events.next().await {
2223                        if response_latency.is_none() {
2224                            response_latency = Some(request_start.elapsed());
2225                        }
2226                        let event = event?;
2227
2228                        this.update(&mut cx, |this, cx| {
2229                            let message_ix = this
2230                                .message_anchors
2231                                .iter()
2232                                .position(|message| message.id == assistant_message_id)?;
2233                            this.buffer.update(cx, |buffer, cx| {
2234                                let message_old_end_offset = this.message_anchors[message_ix + 1..]
2235                                    .iter()
2236                                    .find(|message| message.start.is_valid(buffer))
2237                                    .map_or(buffer.len(), |message| {
2238                                        message.start.to_offset(buffer).saturating_sub(1)
2239                                    });
2240
2241                                match event {
2242                                    LanguageModelCompletionEvent::StartMessage { .. } => {}
2243                                    LanguageModelCompletionEvent::Stop(reason) => {
2244                                        stop_reason = reason;
2245                                    }
2246                                    LanguageModelCompletionEvent::Text(chunk) => {
2247                                        buffer.edit(
2248                                            [(
2249                                                message_old_end_offset..message_old_end_offset,
2250                                                chunk,
2251                                            )],
2252                                            None,
2253                                            cx,
2254                                        );
2255                                    }
2256                                    LanguageModelCompletionEvent::ToolUse(_) => {}
2257                                }
2258                            });
2259
2260                            cx.emit(ContextEvent::StreamedCompletion);
2261
2262                            Some(())
2263                        })?;
2264                        smol::future::yield_now().await;
2265                    }
2266                    this.update(&mut cx, |this, cx| {
2267                        this.pending_completions
2268                            .retain(|completion| completion.id != pending_completion_id);
2269                        this.summarize(false, cx);
2270                        this.update_cache_status_for_completion(cx);
2271                    })?;
2272
2273                    anyhow::Ok(stop_reason)
2274                };
2275
2276                let result = stream_completion.await;
2277
2278                this.update(&mut cx, |this, cx| {
2279                    let error_message = if let Some(error) = result.as_ref().err() {
2280                        if error.is::<PaymentRequiredError>() {
2281                            cx.emit(ContextEvent::ShowPaymentRequiredError);
2282                            this.update_metadata(assistant_message_id, cx, |metadata| {
2283                                metadata.status = MessageStatus::Canceled;
2284                            });
2285                            Some(error.to_string())
2286                        } else if error.is::<MaxMonthlySpendReachedError>() {
2287                            cx.emit(ContextEvent::ShowMaxMonthlySpendReachedError);
2288                            this.update_metadata(assistant_message_id, cx, |metadata| {
2289                                metadata.status = MessageStatus::Canceled;
2290                            });
2291                            Some(error.to_string())
2292                        } else {
2293                            let error_message = error
2294                                .chain()
2295                                .map(|err| err.to_string())
2296                                .collect::<Vec<_>>()
2297                                .join("\n");
2298                            cx.emit(ContextEvent::ShowAssistError(SharedString::from(
2299                                error_message.clone(),
2300                            )));
2301                            this.update_metadata(assistant_message_id, cx, |metadata| {
2302                                metadata.status =
2303                                    MessageStatus::Error(SharedString::from(error_message.clone()));
2304                            });
2305                            Some(error_message)
2306                        }
2307                    } else {
2308                        this.update_metadata(assistant_message_id, cx, |metadata| {
2309                            metadata.status = MessageStatus::Done;
2310                        });
2311                        None
2312                    };
2313
2314                    let language_name = this
2315                        .buffer
2316                        .read(cx)
2317                        .language()
2318                        .map(|language| language.name());
2319                    report_assistant_event(
2320                        AssistantEvent {
2321                            conversation_id: Some(this.id.0.clone()),
2322                            kind: AssistantKind::Panel,
2323                            phase: AssistantPhase::Response,
2324                            message_id: None,
2325                            model: model.telemetry_id(),
2326                            model_provider: model.provider_id().to_string(),
2327                            response_latency,
2328                            error_message,
2329                            language_name: language_name.map(|name| name.to_proto()),
2330                        },
2331                        this.telemetry.clone(),
2332                        cx.http_client(),
2333                        model.api_key(cx),
2334                        cx.background_executor(),
2335                    );
2336
2337                    if let Ok(stop_reason) = result {
2338                        match stop_reason {
2339                            StopReason::ToolUse => {}
2340                            StopReason::EndTurn => {}
2341                            StopReason::MaxTokens => {}
2342                        }
2343                    }
2344                })
2345                .ok();
2346            }
2347        });
2348
2349        self.pending_completions.push(PendingCompletion {
2350            id: pending_completion_id,
2351            assistant_message_id: assistant_message.id,
2352            _task: task,
2353        });
2354
2355        Some(user_message)
2356    }
2357
2358    pub fn to_completion_request(
2359        &self,
2360        request_type: RequestType,
2361        cx: &App,
2362    ) -> LanguageModelRequest {
2363        let buffer = self.buffer.read(cx);
2364
2365        let mut contents = self.contents(cx).peekable();
2366
2367        fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2368            let text: String = buffer.text_for_range(range.clone()).collect();
2369            if text.trim().is_empty() {
2370                None
2371            } else {
2372                Some(text)
2373            }
2374        }
2375
2376        let mut completion_request = LanguageModelRequest {
2377            messages: Vec::new(),
2378            tools: Vec::new(),
2379            stop: Vec::new(),
2380            temperature: None,
2381        };
2382        for message in self.messages(cx) {
2383            if message.status != MessageStatus::Done {
2384                continue;
2385            }
2386
2387            let mut offset = message.offset_range.start;
2388            let mut request_message = LanguageModelRequestMessage {
2389                role: message.role,
2390                content: Vec::new(),
2391                cache: message
2392                    .cache
2393                    .as_ref()
2394                    .map_or(false, |cache| cache.is_anchor),
2395            };
2396
2397            while let Some(content) = contents.peek() {
2398                if content
2399                    .range()
2400                    .end
2401                    .cmp(&message.anchor_range.end, buffer)
2402                    .is_lt()
2403                {
2404                    let content = contents.next().unwrap();
2405                    let range = content.range().to_offset(buffer);
2406                    request_message.content.extend(
2407                        collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2408                    );
2409
2410                    match content {
2411                        Content::Image { image, .. } => {
2412                            if let Some(image) = image.clone().now_or_never().flatten() {
2413                                request_message
2414                                    .content
2415                                    .push(language_model::MessageContent::Image(image));
2416                            }
2417                        }
2418                    }
2419
2420                    offset = range.end;
2421                } else {
2422                    break;
2423                }
2424            }
2425
2426            request_message.content.extend(
2427                collect_text_content(buffer, offset..message.offset_range.end)
2428                    .map(MessageContent::Text),
2429            );
2430
2431            completion_request.messages.push(request_message);
2432        }
2433
2434        if let RequestType::SuggestEdits = request_type {
2435            if let Ok(preamble) = self.prompt_builder.generate_suggest_edits_prompt() {
2436                let last_elem_index = completion_request.messages.len();
2437
2438                completion_request
2439                    .messages
2440                    .push(LanguageModelRequestMessage {
2441                        role: Role::User,
2442                        content: vec![MessageContent::Text(preamble)],
2443                        cache: false,
2444                    });
2445
2446                // The preamble message should be sent right before the last actual user message.
2447                completion_request
2448                    .messages
2449                    .swap(last_elem_index, last_elem_index.saturating_sub(1));
2450            }
2451        }
2452
2453        completion_request
2454    }
2455
2456    pub fn cancel_last_assist(&mut self, cx: &mut Context<Self>) -> bool {
2457        if let Some(pending_completion) = self.pending_completions.pop() {
2458            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2459                if metadata.status == MessageStatus::Pending {
2460                    metadata.status = MessageStatus::Canceled;
2461                }
2462            });
2463            true
2464        } else {
2465            false
2466        }
2467    }
2468
2469    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2470        for id in &ids {
2471            if let Some(metadata) = self.messages_metadata.get(id) {
2472                let role = metadata.role.cycle();
2473                self.update_metadata(*id, cx, |metadata| metadata.role = role);
2474            }
2475        }
2476
2477        self.message_roles_updated(ids, cx);
2478    }
2479
2480    fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2481        let mut ranges = Vec::new();
2482        for message in self.messages(cx) {
2483            if ids.contains(&message.id) {
2484                ranges.push(message.anchor_range.clone());
2485            }
2486        }
2487
2488        let buffer = self.buffer.read(cx).text_snapshot();
2489        let mut updated = Vec::new();
2490        let mut removed = Vec::new();
2491        for range in ranges {
2492            self.reparse_patches_in_range(range, &buffer, &mut updated, &mut removed, cx);
2493        }
2494
2495        if !updated.is_empty() || !removed.is_empty() {
2496            cx.emit(ContextEvent::PatchesUpdated { removed, updated })
2497        }
2498    }
2499
2500    pub fn update_metadata(
2501        &mut self,
2502        id: MessageId,
2503        cx: &mut Context<Self>,
2504        f: impl FnOnce(&mut MessageMetadata),
2505    ) {
2506        let version = self.version.clone();
2507        let timestamp = self.next_timestamp();
2508        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2509            f(metadata);
2510            metadata.timestamp = timestamp;
2511            let operation = ContextOperation::UpdateMessage {
2512                message_id: id,
2513                metadata: metadata.clone(),
2514                version,
2515            };
2516            self.push_op(operation, cx);
2517            cx.emit(ContextEvent::MessagesEdited);
2518            cx.notify();
2519        }
2520    }
2521
2522    pub fn insert_message_after(
2523        &mut self,
2524        message_id: MessageId,
2525        role: Role,
2526        status: MessageStatus,
2527        cx: &mut Context<Self>,
2528    ) -> Option<MessageAnchor> {
2529        if let Some(prev_message_ix) = self
2530            .message_anchors
2531            .iter()
2532            .position(|message| message.id == message_id)
2533        {
2534            // Find the next valid message after the one we were given.
2535            let mut next_message_ix = prev_message_ix + 1;
2536            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2537                if next_message.start.is_valid(self.buffer.read(cx)) {
2538                    break;
2539                }
2540                next_message_ix += 1;
2541            }
2542
2543            let buffer = self.buffer.read(cx);
2544            let offset = self
2545                .message_anchors
2546                .get(next_message_ix)
2547                .map_or(buffer.len(), |message| {
2548                    buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
2549                });
2550            Some(self.insert_message_at_offset(offset, role, status, cx))
2551        } else {
2552            None
2553        }
2554    }
2555
2556    fn insert_message_at_offset(
2557        &mut self,
2558        offset: usize,
2559        role: Role,
2560        status: MessageStatus,
2561        cx: &mut Context<Self>,
2562    ) -> MessageAnchor {
2563        let start = self.buffer.update(cx, |buffer, cx| {
2564            buffer.edit([(offset..offset, "\n")], None, cx);
2565            buffer.anchor_before(offset + 1)
2566        });
2567
2568        let version = self.version.clone();
2569        let anchor = MessageAnchor {
2570            id: MessageId(self.next_timestamp()),
2571            start,
2572        };
2573        let metadata = MessageMetadata {
2574            role,
2575            status,
2576            timestamp: anchor.id.0,
2577            cache: None,
2578        };
2579        self.insert_message(anchor.clone(), metadata.clone(), cx);
2580        self.push_op(
2581            ContextOperation::InsertMessage {
2582                anchor: anchor.clone(),
2583                metadata,
2584                version,
2585            },
2586            cx,
2587        );
2588        anchor
2589    }
2590
2591    pub fn insert_content(&mut self, content: Content, cx: &mut Context<Self>) {
2592        let buffer = self.buffer.read(cx);
2593        let insertion_ix = match self
2594            .contents
2595            .binary_search_by(|probe| probe.cmp(&content, buffer))
2596        {
2597            Ok(ix) => {
2598                self.contents.remove(ix);
2599                ix
2600            }
2601            Err(ix) => ix,
2602        };
2603        self.contents.insert(insertion_ix, content);
2604        cx.emit(ContextEvent::MessagesEdited);
2605    }
2606
2607    pub fn contents<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Content> {
2608        let buffer = self.buffer.read(cx);
2609        self.contents
2610            .iter()
2611            .filter(|content| {
2612                let range = content.range();
2613                range.start.is_valid(buffer) && range.end.is_valid(buffer)
2614            })
2615            .cloned()
2616    }
2617
2618    pub fn split_message(
2619        &mut self,
2620        range: Range<usize>,
2621        cx: &mut Context<Self>,
2622    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2623        let start_message = self.message_for_offset(range.start, cx);
2624        let end_message = self.message_for_offset(range.end, cx);
2625        if let Some((start_message, end_message)) = start_message.zip(end_message) {
2626            // Prevent splitting when range spans multiple messages.
2627            if start_message.id != end_message.id {
2628                return (None, None);
2629            }
2630
2631            let message = start_message;
2632            let role = message.role;
2633            let mut edited_buffer = false;
2634
2635            let mut suffix_start = None;
2636
2637            // TODO: why did this start panicking?
2638            if range.start > message.offset_range.start
2639                && range.end < message.offset_range.end.saturating_sub(1)
2640            {
2641                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2642                    suffix_start = Some(range.end + 1);
2643                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2644                    suffix_start = Some(range.end);
2645                }
2646            }
2647
2648            let version = self.version.clone();
2649            let suffix = if let Some(suffix_start) = suffix_start {
2650                MessageAnchor {
2651                    id: MessageId(self.next_timestamp()),
2652                    start: self.buffer.read(cx).anchor_before(suffix_start),
2653                }
2654            } else {
2655                self.buffer.update(cx, |buffer, cx| {
2656                    buffer.edit([(range.end..range.end, "\n")], None, cx);
2657                });
2658                edited_buffer = true;
2659                MessageAnchor {
2660                    id: MessageId(self.next_timestamp()),
2661                    start: self.buffer.read(cx).anchor_before(range.end + 1),
2662                }
2663            };
2664
2665            let suffix_metadata = MessageMetadata {
2666                role,
2667                status: MessageStatus::Done,
2668                timestamp: suffix.id.0,
2669                cache: None,
2670            };
2671            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2672            self.push_op(
2673                ContextOperation::InsertMessage {
2674                    anchor: suffix.clone(),
2675                    metadata: suffix_metadata,
2676                    version,
2677                },
2678                cx,
2679            );
2680
2681            let new_messages =
2682                if range.start == range.end || range.start == message.offset_range.start {
2683                    (None, Some(suffix))
2684                } else {
2685                    let mut prefix_end = None;
2686                    if range.start > message.offset_range.start
2687                        && range.end < message.offset_range.end - 1
2688                    {
2689                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2690                            prefix_end = Some(range.start + 1);
2691                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2692                            == Some('\n')
2693                        {
2694                            prefix_end = Some(range.start);
2695                        }
2696                    }
2697
2698                    let version = self.version.clone();
2699                    let selection = if let Some(prefix_end) = prefix_end {
2700                        MessageAnchor {
2701                            id: MessageId(self.next_timestamp()),
2702                            start: self.buffer.read(cx).anchor_before(prefix_end),
2703                        }
2704                    } else {
2705                        self.buffer.update(cx, |buffer, cx| {
2706                            buffer.edit([(range.start..range.start, "\n")], None, cx)
2707                        });
2708                        edited_buffer = true;
2709                        MessageAnchor {
2710                            id: MessageId(self.next_timestamp()),
2711                            start: self.buffer.read(cx).anchor_before(range.end + 1),
2712                        }
2713                    };
2714
2715                    let selection_metadata = MessageMetadata {
2716                        role,
2717                        status: MessageStatus::Done,
2718                        timestamp: selection.id.0,
2719                        cache: None,
2720                    };
2721                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2722                    self.push_op(
2723                        ContextOperation::InsertMessage {
2724                            anchor: selection.clone(),
2725                            metadata: selection_metadata,
2726                            version,
2727                        },
2728                        cx,
2729                    );
2730
2731                    (Some(selection), Some(suffix))
2732                };
2733
2734            if !edited_buffer {
2735                cx.emit(ContextEvent::MessagesEdited);
2736            }
2737            new_messages
2738        } else {
2739            (None, None)
2740        }
2741    }
2742
2743    fn insert_message(
2744        &mut self,
2745        new_anchor: MessageAnchor,
2746        new_metadata: MessageMetadata,
2747        cx: &mut Context<Self>,
2748    ) {
2749        cx.emit(ContextEvent::MessagesEdited);
2750
2751        self.messages_metadata.insert(new_anchor.id, new_metadata);
2752
2753        let buffer = self.buffer.read(cx);
2754        let insertion_ix = self
2755            .message_anchors
2756            .iter()
2757            .position(|anchor| {
2758                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2759                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2760            })
2761            .unwrap_or(self.message_anchors.len());
2762        self.message_anchors.insert(insertion_ix, new_anchor);
2763    }
2764
2765    pub fn summarize(&mut self, replace_old: bool, cx: &mut Context<Self>) {
2766        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
2767            return;
2768        };
2769        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
2770            return;
2771        };
2772
2773        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
2774            if !provider.is_authenticated(cx) {
2775                return;
2776            }
2777
2778            let mut request = self.to_completion_request(RequestType::Chat, cx);
2779            request.messages.push(LanguageModelRequestMessage {
2780                role: Role::User,
2781                content: vec![
2782                    "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:`"
2783                        .into(),
2784                ],
2785                cache: false,
2786            });
2787
2788            self.pending_summary = cx.spawn(|this, mut cx| {
2789                async move {
2790                    let stream = model.stream_completion_text(request, &cx);
2791                    let mut messages = stream.await?;
2792
2793                    let mut replaced = !replace_old;
2794                    while let Some(message) = messages.stream.next().await {
2795                        let text = message?;
2796                        let mut lines = text.lines();
2797                        this.update(&mut cx, |this, cx| {
2798                            let version = this.version.clone();
2799                            let timestamp = this.next_timestamp();
2800                            let summary = this.summary.get_or_insert(ContextSummary::default());
2801                            if !replaced && replace_old {
2802                                summary.text.clear();
2803                                replaced = true;
2804                            }
2805                            summary.text.extend(lines.next());
2806                            summary.timestamp = timestamp;
2807                            let operation = ContextOperation::UpdateSummary {
2808                                summary: summary.clone(),
2809                                version,
2810                            };
2811                            this.push_op(operation, cx);
2812                            cx.emit(ContextEvent::SummaryChanged);
2813                        })?;
2814
2815                        // Stop if the LLM generated multiple lines.
2816                        if lines.next().is_some() {
2817                            break;
2818                        }
2819                    }
2820
2821                    this.update(&mut cx, |this, cx| {
2822                        let version = this.version.clone();
2823                        let timestamp = this.next_timestamp();
2824                        if let Some(summary) = this.summary.as_mut() {
2825                            summary.done = true;
2826                            summary.timestamp = timestamp;
2827                            let operation = ContextOperation::UpdateSummary {
2828                                summary: summary.clone(),
2829                                version,
2830                            };
2831                            this.push_op(operation, cx);
2832                            cx.emit(ContextEvent::SummaryChanged);
2833                        }
2834                    })?;
2835
2836                    anyhow::Ok(())
2837                }
2838                .log_err()
2839            });
2840        }
2841    }
2842
2843    fn message_for_offset(&self, offset: usize, cx: &App) -> Option<Message> {
2844        self.messages_for_offsets([offset], cx).pop()
2845    }
2846
2847    pub fn messages_for_offsets(
2848        &self,
2849        offsets: impl IntoIterator<Item = usize>,
2850        cx: &App,
2851    ) -> Vec<Message> {
2852        let mut result = Vec::new();
2853
2854        let mut messages = self.messages(cx).peekable();
2855        let mut offsets = offsets.into_iter().peekable();
2856        let mut current_message = messages.next();
2857        while let Some(offset) = offsets.next() {
2858            // Locate the message that contains the offset.
2859            while current_message.as_ref().map_or(false, |message| {
2860                !message.offset_range.contains(&offset) && messages.peek().is_some()
2861            }) {
2862                current_message = messages.next();
2863            }
2864            let Some(message) = current_message.as_ref() else {
2865                break;
2866            };
2867
2868            // Skip offsets that are in the same message.
2869            while offsets.peek().map_or(false, |offset| {
2870                message.offset_range.contains(offset) || messages.peek().is_none()
2871            }) {
2872                offsets.next();
2873            }
2874
2875            result.push(message.clone());
2876        }
2877        result
2878    }
2879
2880    fn messages_from_anchors<'a>(
2881        &'a self,
2882        message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2883        cx: &'a App,
2884    ) -> impl 'a + Iterator<Item = Message> {
2885        let buffer = self.buffer.read(cx);
2886
2887        Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2888    }
2889
2890    pub fn messages<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Message> {
2891        self.messages_from_anchors(self.message_anchors.iter(), cx)
2892    }
2893
2894    pub fn messages_from_iters<'a>(
2895        buffer: &'a Buffer,
2896        metadata: &'a HashMap<MessageId, MessageMetadata>,
2897        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2898    ) -> impl 'a + Iterator<Item = Message> {
2899        let mut messages = messages.peekable();
2900
2901        iter::from_fn(move || {
2902            if let Some((start_ix, message_anchor)) = messages.next() {
2903                let metadata = metadata.get(&message_anchor.id)?;
2904
2905                let message_start = message_anchor.start.to_offset(buffer);
2906                let mut message_end = None;
2907                let mut end_ix = start_ix;
2908                while let Some((_, next_message)) = messages.peek() {
2909                    if next_message.start.is_valid(buffer) {
2910                        message_end = Some(next_message.start);
2911                        break;
2912                    } else {
2913                        end_ix += 1;
2914                        messages.next();
2915                    }
2916                }
2917                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2918                let message_end = message_end_anchor.to_offset(buffer);
2919
2920                return Some(Message {
2921                    index_range: start_ix..end_ix,
2922                    offset_range: message_start..message_end,
2923                    anchor_range: message_anchor.start..message_end_anchor,
2924                    id: message_anchor.id,
2925                    role: metadata.role,
2926                    status: metadata.status.clone(),
2927                    cache: metadata.cache.clone(),
2928                });
2929            }
2930            None
2931        })
2932    }
2933
2934    pub fn save(
2935        &mut self,
2936        debounce: Option<Duration>,
2937        fs: Arc<dyn Fs>,
2938        cx: &mut Context<AssistantContext>,
2939    ) {
2940        if self.replica_id() != ReplicaId::default() {
2941            // Prevent saving a remote context for now.
2942            return;
2943        }
2944
2945        self.pending_save = cx.spawn(|this, mut cx| async move {
2946            if let Some(debounce) = debounce {
2947                cx.background_executor().timer(debounce).await;
2948            }
2949
2950            let (old_path, summary) = this.read_with(&cx, |this, _| {
2951                let path = this.path.clone();
2952                let summary = if let Some(summary) = this.summary.as_ref() {
2953                    if summary.done {
2954                        Some(summary.text.clone())
2955                    } else {
2956                        None
2957                    }
2958                } else {
2959                    None
2960                };
2961                (path, summary)
2962            })?;
2963
2964            if let Some(summary) = summary {
2965                let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2966                let mut discriminant = 1;
2967                let mut new_path;
2968                loop {
2969                    new_path = contexts_dir().join(&format!(
2970                        "{} - {}.zed.json",
2971                        summary.trim(),
2972                        discriminant
2973                    ));
2974                    if fs.is_file(&new_path).await {
2975                        discriminant += 1;
2976                    } else {
2977                        break;
2978                    }
2979                }
2980
2981                fs.create_dir(contexts_dir().as_ref()).await?;
2982                fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
2983                    .await?;
2984                if let Some(old_path) = old_path {
2985                    if new_path != old_path {
2986                        fs.remove_file(
2987                            &old_path,
2988                            RemoveOptions {
2989                                recursive: false,
2990                                ignore_if_not_exists: true,
2991                            },
2992                        )
2993                        .await?;
2994                    }
2995                }
2996
2997                this.update(&mut cx, |this, _| this.path = Some(new_path))?;
2998            }
2999
3000            Ok(())
3001        });
3002    }
3003
3004    pub fn custom_summary(&mut self, custom_summary: String, cx: &mut Context<Self>) {
3005        let timestamp = self.next_timestamp();
3006        let summary = self.summary.get_or_insert(ContextSummary::default());
3007        summary.timestamp = timestamp;
3008        summary.done = true;
3009        summary.text = custom_summary;
3010        cx.emit(ContextEvent::SummaryChanged);
3011    }
3012}
3013
3014fn trimmed_text_in_range(buffer: &BufferSnapshot, range: Range<text::Anchor>) -> String {
3015    let mut is_start = true;
3016    let mut content = buffer
3017        .text_for_range(range)
3018        .map(|mut chunk| {
3019            if is_start {
3020                chunk = chunk.trim_start_matches('\n');
3021                if !chunk.is_empty() {
3022                    is_start = false;
3023                }
3024            }
3025            chunk
3026        })
3027        .collect::<String>();
3028    content.truncate(content.trim_end().len());
3029    content
3030}
3031
3032#[derive(Debug, Default)]
3033pub struct ContextVersion {
3034    context: clock::Global,
3035    buffer: clock::Global,
3036}
3037
3038impl ContextVersion {
3039    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
3040        Self {
3041            context: language::proto::deserialize_version(&proto.context_version),
3042            buffer: language::proto::deserialize_version(&proto.buffer_version),
3043        }
3044    }
3045
3046    pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
3047        proto::ContextVersion {
3048            context_id: context_id.to_proto(),
3049            context_version: language::proto::serialize_version(&self.context),
3050            buffer_version: language::proto::serialize_version(&self.buffer),
3051        }
3052    }
3053}
3054
3055#[derive(Debug, Clone)]
3056pub struct ParsedSlashCommand {
3057    pub name: String,
3058    pub arguments: SmallVec<[String; 3]>,
3059    pub status: PendingSlashCommandStatus,
3060    pub source_range: Range<language::Anchor>,
3061}
3062
3063#[derive(Debug)]
3064pub struct InvokedSlashCommand {
3065    pub name: SharedString,
3066    pub range: Range<language::Anchor>,
3067    pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
3068    pub status: InvokedSlashCommandStatus,
3069    pub transaction: Option<language::TransactionId>,
3070    timestamp: clock::Lamport,
3071}
3072
3073#[derive(Debug)]
3074pub enum InvokedSlashCommandStatus {
3075    Running(Task<()>),
3076    Error(SharedString),
3077    Finished,
3078}
3079
3080#[derive(Debug, Clone)]
3081pub enum PendingSlashCommandStatus {
3082    Idle,
3083    Running { _task: Shared<Task<()>> },
3084    Error(String),
3085}
3086
3087#[derive(Debug, Clone)]
3088pub struct PendingToolUse {
3089    pub id: LanguageModelToolUseId,
3090    pub name: String,
3091    pub input: serde_json::Value,
3092    pub status: PendingToolUseStatus,
3093    pub source_range: Range<language::Anchor>,
3094}
3095
3096#[derive(Debug, Clone)]
3097pub enum PendingToolUseStatus {
3098    Idle,
3099    Running { _task: Shared<Task<()>> },
3100    Error(String),
3101}
3102
3103impl PendingToolUseStatus {
3104    pub fn is_idle(&self) -> bool {
3105        matches!(self, PendingToolUseStatus::Idle)
3106    }
3107}
3108
3109#[derive(Serialize, Deserialize)]
3110pub struct SavedMessage {
3111    pub id: MessageId,
3112    pub start: usize,
3113    pub metadata: MessageMetadata,
3114}
3115
3116#[derive(Serialize, Deserialize)]
3117pub struct SavedContext {
3118    pub id: Option<ContextId>,
3119    pub zed: String,
3120    pub version: String,
3121    pub text: String,
3122    pub messages: Vec<SavedMessage>,
3123    pub summary: String,
3124    pub slash_command_output_sections:
3125        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3126}
3127
3128impl SavedContext {
3129    pub const VERSION: &'static str = "0.4.0";
3130
3131    pub fn from_json(json: &str) -> Result<Self> {
3132        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3133        match saved_context_json
3134            .get("version")
3135            .ok_or_else(|| anyhow!("version not found"))?
3136        {
3137            serde_json::Value::String(version) => match version.as_str() {
3138                SavedContext::VERSION => {
3139                    Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
3140                }
3141                SavedContextV0_3_0::VERSION => {
3142                    let saved_context =
3143                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3144                    Ok(saved_context.upgrade())
3145                }
3146                SavedContextV0_2_0::VERSION => {
3147                    let saved_context =
3148                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3149                    Ok(saved_context.upgrade())
3150                }
3151                SavedContextV0_1_0::VERSION => {
3152                    let saved_context =
3153                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3154                    Ok(saved_context.upgrade())
3155                }
3156                _ => Err(anyhow!("unrecognized saved context version: {}", version)),
3157            },
3158            _ => Err(anyhow!("version not found on saved context")),
3159        }
3160    }
3161
3162    fn into_ops(
3163        self,
3164        buffer: &Entity<Buffer>,
3165        cx: &mut Context<AssistantContext>,
3166    ) -> Vec<ContextOperation> {
3167        let mut operations = Vec::new();
3168        let mut version = clock::Global::new();
3169        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3170
3171        let mut first_message_metadata = None;
3172        for message in self.messages {
3173            if message.id == MessageId(clock::Lamport::default()) {
3174                first_message_metadata = Some(message.metadata);
3175            } else {
3176                operations.push(ContextOperation::InsertMessage {
3177                    anchor: MessageAnchor {
3178                        id: message.id,
3179                        start: buffer.read(cx).anchor_before(message.start),
3180                    },
3181                    metadata: MessageMetadata {
3182                        role: message.metadata.role,
3183                        status: message.metadata.status,
3184                        timestamp: message.metadata.timestamp,
3185                        cache: None,
3186                    },
3187                    version: version.clone(),
3188                });
3189                version.observe(message.id.0);
3190                next_timestamp.observe(message.id.0);
3191            }
3192        }
3193
3194        if let Some(metadata) = first_message_metadata {
3195            let timestamp = next_timestamp.tick();
3196            operations.push(ContextOperation::UpdateMessage {
3197                message_id: MessageId(clock::Lamport::default()),
3198                metadata: MessageMetadata {
3199                    role: metadata.role,
3200                    status: metadata.status,
3201                    timestamp,
3202                    cache: None,
3203                },
3204                version: version.clone(),
3205            });
3206            version.observe(timestamp);
3207        }
3208
3209        let buffer = buffer.read(cx);
3210        for section in self.slash_command_output_sections {
3211            let timestamp = next_timestamp.tick();
3212            operations.push(ContextOperation::SlashCommandOutputSectionAdded {
3213                timestamp,
3214                section: SlashCommandOutputSection {
3215                    range: buffer.anchor_after(section.range.start)
3216                        ..buffer.anchor_before(section.range.end),
3217                    icon: section.icon,
3218                    label: section.label,
3219                    metadata: section.metadata,
3220                },
3221                version: version.clone(),
3222            });
3223
3224            version.observe(timestamp);
3225        }
3226
3227        let timestamp = next_timestamp.tick();
3228        operations.push(ContextOperation::UpdateSummary {
3229            summary: ContextSummary {
3230                text: self.summary,
3231                done: true,
3232                timestamp,
3233            },
3234            version: version.clone(),
3235        });
3236        version.observe(timestamp);
3237
3238        operations
3239    }
3240}
3241
3242#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3243struct SavedMessageIdPreV0_4_0(usize);
3244
3245#[derive(Serialize, Deserialize)]
3246struct SavedMessagePreV0_4_0 {
3247    id: SavedMessageIdPreV0_4_0,
3248    start: usize,
3249}
3250
3251#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3252struct SavedMessageMetadataPreV0_4_0 {
3253    role: Role,
3254    status: MessageStatus,
3255}
3256
3257#[derive(Serialize, Deserialize)]
3258struct SavedContextV0_3_0 {
3259    id: Option<ContextId>,
3260    zed: String,
3261    version: String,
3262    text: String,
3263    messages: Vec<SavedMessagePreV0_4_0>,
3264    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3265    summary: String,
3266    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3267}
3268
3269impl SavedContextV0_3_0 {
3270    const VERSION: &'static str = "0.3.0";
3271
3272    fn upgrade(self) -> SavedContext {
3273        SavedContext {
3274            id: self.id,
3275            zed: self.zed,
3276            version: SavedContext::VERSION.into(),
3277            text: self.text,
3278            messages: self
3279                .messages
3280                .into_iter()
3281                .filter_map(|message| {
3282                    let metadata = self.message_metadata.get(&message.id)?;
3283                    let timestamp = clock::Lamport {
3284                        replica_id: ReplicaId::default(),
3285                        value: message.id.0 as u32,
3286                    };
3287                    Some(SavedMessage {
3288                        id: MessageId(timestamp),
3289                        start: message.start,
3290                        metadata: MessageMetadata {
3291                            role: metadata.role,
3292                            status: metadata.status.clone(),
3293                            timestamp,
3294                            cache: None,
3295                        },
3296                    })
3297                })
3298                .collect(),
3299            summary: self.summary,
3300            slash_command_output_sections: self.slash_command_output_sections,
3301        }
3302    }
3303}
3304
3305#[derive(Serialize, Deserialize)]
3306struct SavedContextV0_2_0 {
3307    id: Option<ContextId>,
3308    zed: String,
3309    version: String,
3310    text: String,
3311    messages: Vec<SavedMessagePreV0_4_0>,
3312    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3313    summary: String,
3314}
3315
3316impl SavedContextV0_2_0 {
3317    const VERSION: &'static str = "0.2.0";
3318
3319    fn upgrade(self) -> SavedContext {
3320        SavedContextV0_3_0 {
3321            id: self.id,
3322            zed: self.zed,
3323            version: SavedContextV0_3_0::VERSION.to_string(),
3324            text: self.text,
3325            messages: self.messages,
3326            message_metadata: self.message_metadata,
3327            summary: self.summary,
3328            slash_command_output_sections: Vec::new(),
3329        }
3330        .upgrade()
3331    }
3332}
3333
3334#[derive(Serialize, Deserialize)]
3335struct SavedContextV0_1_0 {
3336    id: Option<ContextId>,
3337    zed: String,
3338    version: String,
3339    text: String,
3340    messages: Vec<SavedMessagePreV0_4_0>,
3341    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3342    summary: String,
3343    api_url: Option<String>,
3344    model: OpenAiModel,
3345}
3346
3347impl SavedContextV0_1_0 {
3348    const VERSION: &'static str = "0.1.0";
3349
3350    fn upgrade(self) -> SavedContext {
3351        SavedContextV0_2_0 {
3352            id: self.id,
3353            zed: self.zed,
3354            version: SavedContextV0_2_0::VERSION.to_string(),
3355            text: self.text,
3356            messages: self.messages,
3357            message_metadata: self.message_metadata,
3358            summary: self.summary,
3359        }
3360        .upgrade()
3361    }
3362}
3363
3364#[derive(Clone)]
3365pub struct SavedContextMetadata {
3366    pub title: String,
3367    pub path: PathBuf,
3368    pub mtime: chrono::DateTime<chrono::Local>,
3369}