context.rs

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