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