context.rs

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