context.rs

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