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