context.rs

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