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