context.rs

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