context.rs

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