context.rs

   1#[cfg(test)]
   2mod context_tests;
   3
   4use crate::{
   5    prompts::PromptBuilder, slash_command::SlashCommandLine, workflow::WorkflowStep, MessageId,
   6    MessageStatus,
   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::{future::Shared, stream::FuturesUnordered, FutureExt, StreamExt};
  17use gpui::{
  18    AppContext, Context as _, EventEmitter, Image, Model, ModelContext, RenderImage, SharedString,
  19    Subscription, Task,
  20};
  21
  22use language::{AnchorRangeExt, Bias, Buffer, LanguageRegistry, OffsetRangeExt, Point, ToOffset};
  23use language_model::{
  24    LanguageModelImage, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
  25    Role,
  26};
  27use open_ai::Model as OpenAiModel;
  28use paths::{context_images_dir, contexts_dir};
  29use project::Project;
  30use serde::{Deserialize, Serialize};
  31use smallvec::SmallVec;
  32use std::{
  33    cmp::Ordering,
  34    collections::hash_map,
  35    fmt::Debug,
  36    iter, mem,
  37    ops::Range,
  38    path::{Path, PathBuf},
  39    sync::Arc,
  40    time::{Duration, Instant},
  41};
  42use telemetry_events::AssistantKind;
  43use util::{post_inc, ResultExt, TryFutureExt};
  44use uuid::Uuid;
  45
  46#[derive(Clone, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  47pub struct ContextId(String);
  48
  49impl ContextId {
  50    pub fn new() -> Self {
  51        Self(Uuid::new_v4().to_string())
  52    }
  53
  54    pub fn from_proto(id: String) -> Self {
  55        Self(id)
  56    }
  57
  58    pub fn to_proto(&self) -> String {
  59        self.0.clone()
  60    }
  61}
  62
  63#[derive(Clone, Debug)]
  64pub enum ContextOperation {
  65    InsertMessage {
  66        anchor: MessageAnchor,
  67        metadata: MessageMetadata,
  68        version: clock::Global,
  69    },
  70    UpdateMessage {
  71        message_id: MessageId,
  72        metadata: MessageMetadata,
  73        version: clock::Global,
  74    },
  75    UpdateSummary {
  76        summary: ContextSummary,
  77        version: clock::Global,
  78    },
  79    SlashCommandFinished {
  80        id: SlashCommandId,
  81        output_range: Range<language::Anchor>,
  82        sections: Vec<SlashCommandOutputSection<language::Anchor>>,
  83        version: clock::Global,
  84    },
  85    BufferOperation(language::Operation),
  86}
  87
  88impl ContextOperation {
  89    pub fn from_proto(op: proto::ContextOperation) -> Result<Self> {
  90        match op.variant.context("invalid variant")? {
  91            proto::context_operation::Variant::InsertMessage(insert) => {
  92                let message = insert.message.context("invalid message")?;
  93                let id = MessageId(language::proto::deserialize_timestamp(
  94                    message.id.context("invalid id")?,
  95                ));
  96                Ok(Self::InsertMessage {
  97                    anchor: MessageAnchor {
  98                        id,
  99                        start: language::proto::deserialize_anchor(
 100                            message.start.context("invalid anchor")?,
 101                        )
 102                        .context("invalid anchor")?,
 103                    },
 104                    metadata: MessageMetadata {
 105                        role: Role::from_proto(message.role),
 106                        status: MessageStatus::from_proto(
 107                            message.status.context("invalid status")?,
 108                        ),
 109                        timestamp: id.0,
 110                    },
 111                    version: language::proto::deserialize_version(&insert.version),
 112                })
 113            }
 114            proto::context_operation::Variant::UpdateMessage(update) => Ok(Self::UpdateMessage {
 115                message_id: MessageId(language::proto::deserialize_timestamp(
 116                    update.message_id.context("invalid message id")?,
 117                )),
 118                metadata: MessageMetadata {
 119                    role: Role::from_proto(update.role),
 120                    status: MessageStatus::from_proto(update.status.context("invalid status")?),
 121                    timestamp: language::proto::deserialize_timestamp(
 122                        update.timestamp.context("invalid timestamp")?,
 123                    ),
 124                },
 125                version: language::proto::deserialize_version(&update.version),
 126            }),
 127            proto::context_operation::Variant::UpdateSummary(update) => Ok(Self::UpdateSummary {
 128                summary: ContextSummary {
 129                    text: update.summary,
 130                    done: update.done,
 131                    timestamp: language::proto::deserialize_timestamp(
 132                        update.timestamp.context("invalid timestamp")?,
 133                    ),
 134                },
 135                version: language::proto::deserialize_version(&update.version),
 136            }),
 137            proto::context_operation::Variant::SlashCommandFinished(finished) => {
 138                Ok(Self::SlashCommandFinished {
 139                    id: SlashCommandId(language::proto::deserialize_timestamp(
 140                        finished.id.context("invalid id")?,
 141                    )),
 142                    output_range: language::proto::deserialize_anchor_range(
 143                        finished.output_range.context("invalid range")?,
 144                    )?,
 145                    sections: finished
 146                        .sections
 147                        .into_iter()
 148                        .map(|section| {
 149                            Ok(SlashCommandOutputSection {
 150                                range: language::proto::deserialize_anchor_range(
 151                                    section.range.context("invalid range")?,
 152                                )?,
 153                                icon: section.icon_name.parse()?,
 154                                label: section.label.into(),
 155                            })
 156                        })
 157                        .collect::<Result<Vec<_>>>()?,
 158                    version: language::proto::deserialize_version(&finished.version),
 159                })
 160            }
 161            proto::context_operation::Variant::BufferOperation(op) => Ok(Self::BufferOperation(
 162                language::proto::deserialize_operation(
 163                    op.operation.context("invalid buffer operation")?,
 164                )?,
 165            )),
 166        }
 167    }
 168
 169    pub fn to_proto(&self) -> proto::ContextOperation {
 170        match self {
 171            Self::InsertMessage {
 172                anchor,
 173                metadata,
 174                version,
 175            } => proto::ContextOperation {
 176                variant: Some(proto::context_operation::Variant::InsertMessage(
 177                    proto::context_operation::InsertMessage {
 178                        message: Some(proto::ContextMessage {
 179                            id: Some(language::proto::serialize_timestamp(anchor.id.0)),
 180                            start: Some(language::proto::serialize_anchor(&anchor.start)),
 181                            role: metadata.role.to_proto() as i32,
 182                            status: Some(metadata.status.to_proto()),
 183                        }),
 184                        version: language::proto::serialize_version(version),
 185                    },
 186                )),
 187            },
 188            Self::UpdateMessage {
 189                message_id,
 190                metadata,
 191                version,
 192            } => proto::ContextOperation {
 193                variant: Some(proto::context_operation::Variant::UpdateMessage(
 194                    proto::context_operation::UpdateMessage {
 195                        message_id: Some(language::proto::serialize_timestamp(message_id.0)),
 196                        role: metadata.role.to_proto() as i32,
 197                        status: Some(metadata.status.to_proto()),
 198                        timestamp: Some(language::proto::serialize_timestamp(metadata.timestamp)),
 199                        version: language::proto::serialize_version(version),
 200                    },
 201                )),
 202            },
 203            Self::UpdateSummary { summary, version } => proto::ContextOperation {
 204                variant: Some(proto::context_operation::Variant::UpdateSummary(
 205                    proto::context_operation::UpdateSummary {
 206                        summary: summary.text.clone(),
 207                        done: summary.done,
 208                        timestamp: Some(language::proto::serialize_timestamp(summary.timestamp)),
 209                        version: language::proto::serialize_version(version),
 210                    },
 211                )),
 212            },
 213            Self::SlashCommandFinished {
 214                id,
 215                output_range,
 216                sections,
 217                version,
 218            } => proto::ContextOperation {
 219                variant: Some(proto::context_operation::Variant::SlashCommandFinished(
 220                    proto::context_operation::SlashCommandFinished {
 221                        id: Some(language::proto::serialize_timestamp(id.0)),
 222                        output_range: Some(language::proto::serialize_anchor_range(
 223                            output_range.clone(),
 224                        )),
 225                        sections: sections
 226                            .iter()
 227                            .map(|section| {
 228                                let icon_name: &'static str = section.icon.into();
 229                                proto::SlashCommandOutputSection {
 230                                    range: Some(language::proto::serialize_anchor_range(
 231                                        section.range.clone(),
 232                                    )),
 233                                    icon_name: icon_name.to_string(),
 234                                    label: section.label.to_string(),
 235                                }
 236                            })
 237                            .collect(),
 238                        version: language::proto::serialize_version(version),
 239                    },
 240                )),
 241            },
 242            Self::BufferOperation(operation) => proto::ContextOperation {
 243                variant: Some(proto::context_operation::Variant::BufferOperation(
 244                    proto::context_operation::BufferOperation {
 245                        operation: Some(language::proto::serialize_operation(operation)),
 246                    },
 247                )),
 248            },
 249        }
 250    }
 251
 252    fn timestamp(&self) -> clock::Lamport {
 253        match self {
 254            Self::InsertMessage { anchor, .. } => anchor.id.0,
 255            Self::UpdateMessage { metadata, .. } => metadata.timestamp,
 256            Self::UpdateSummary { summary, .. } => summary.timestamp,
 257            Self::SlashCommandFinished { id, .. } => id.0,
 258            Self::BufferOperation(_) => {
 259                panic!("reading the timestamp of a buffer operation is not supported")
 260            }
 261        }
 262    }
 263
 264    /// Returns the current version of the context operation.
 265    pub fn version(&self) -> &clock::Global {
 266        match self {
 267            Self::InsertMessage { version, .. }
 268            | Self::UpdateMessage { version, .. }
 269            | Self::UpdateSummary { version, .. }
 270            | Self::SlashCommandFinished { version, .. } => version,
 271            Self::BufferOperation(_) => {
 272                panic!("reading the version of a buffer operation is not supported")
 273            }
 274        }
 275    }
 276}
 277
 278#[derive(Debug, Clone)]
 279pub enum ContextEvent {
 280    ShowAssistError(SharedString),
 281    MessagesEdited,
 282    SummaryChanged,
 283    WorkflowStepsRemoved(Vec<Range<language::Anchor>>),
 284    WorkflowStepUpdated(Range<language::Anchor>),
 285    StreamedCompletion,
 286    PendingSlashCommandsUpdated {
 287        removed: Vec<Range<language::Anchor>>,
 288        updated: Vec<PendingSlashCommand>,
 289    },
 290    SlashCommandFinished {
 291        output_range: Range<language::Anchor>,
 292        sections: Vec<SlashCommandOutputSection<language::Anchor>>,
 293        run_commands_in_output: bool,
 294    },
 295    Operation(ContextOperation),
 296}
 297
 298#[derive(Clone, Default, Debug)]
 299pub struct ContextSummary {
 300    pub text: String,
 301    done: bool,
 302    timestamp: clock::Lamport,
 303}
 304
 305#[derive(Clone, Debug, Eq, PartialEq)]
 306pub struct MessageAnchor {
 307    pub id: MessageId,
 308    pub start: language::Anchor,
 309}
 310
 311#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
 312pub struct MessageMetadata {
 313    pub role: Role,
 314    pub status: MessageStatus,
 315    timestamp: clock::Lamport,
 316}
 317
 318#[derive(Clone, Debug)]
 319pub struct MessageImage {
 320    image_id: u64,
 321    image: Shared<Task<Option<LanguageModelImage>>>,
 322}
 323
 324impl PartialEq for MessageImage {
 325    fn eq(&self, other: &Self) -> bool {
 326        self.image_id == other.image_id
 327    }
 328}
 329
 330impl Eq for MessageImage {}
 331
 332#[derive(Clone, Debug)]
 333pub struct Message {
 334    pub image_offsets: SmallVec<[(usize, MessageImage); 1]>,
 335    pub offset_range: Range<usize>,
 336    pub index_range: Range<usize>,
 337    pub id: MessageId,
 338    pub anchor: language::Anchor,
 339    pub role: Role,
 340    pub status: MessageStatus,
 341}
 342
 343impl Message {
 344    fn to_request_message(&self, buffer: &Buffer) -> LanguageModelRequestMessage {
 345        let mut content = Vec::new();
 346
 347        let mut range_start = self.offset_range.start;
 348        for (image_offset, message_image) in self.image_offsets.iter() {
 349            if *image_offset != range_start {
 350                content.push(
 351                    buffer
 352                        .text_for_range(range_start..*image_offset)
 353                        .collect::<String>()
 354                        .into(),
 355                )
 356            }
 357
 358            if let Some(image) = message_image.image.clone().now_or_never().flatten() {
 359                content.push(language_model::MessageContent::Image(image));
 360            }
 361
 362            range_start = *image_offset;
 363        }
 364        if range_start != self.offset_range.end {
 365            content.push(
 366                buffer
 367                    .text_for_range(range_start..self.offset_range.end)
 368                    .collect::<String>()
 369                    .into(),
 370            )
 371        }
 372
 373        LanguageModelRequestMessage {
 374            role: self.role,
 375            content,
 376        }
 377    }
 378}
 379
 380#[derive(Clone, Debug)]
 381pub struct ImageAnchor {
 382    pub anchor: language::Anchor,
 383    pub image_id: u64,
 384    pub render_image: Arc<RenderImage>,
 385    pub image: Shared<Task<Option<LanguageModelImage>>>,
 386}
 387
 388struct PendingCompletion {
 389    id: usize,
 390    assistant_message_id: MessageId,
 391    _task: Task<()>,
 392}
 393
 394#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
 395pub struct SlashCommandId(clock::Lamport);
 396
 397struct WorkflowStepEntry {
 398    range: Range<language::Anchor>,
 399    step: Model<WorkflowStep>,
 400}
 401
 402pub struct Context {
 403    id: ContextId,
 404    timestamp: clock::Lamport,
 405    version: clock::Global,
 406    pending_ops: Vec<ContextOperation>,
 407    operations: Vec<ContextOperation>,
 408    buffer: Model<Buffer>,
 409    pending_slash_commands: Vec<PendingSlashCommand>,
 410    edits_since_last_slash_command_parse: language::Subscription,
 411    finished_slash_commands: HashSet<SlashCommandId>,
 412    slash_command_output_sections: Vec<SlashCommandOutputSection<language::Anchor>>,
 413    message_anchors: Vec<MessageAnchor>,
 414    images: HashMap<u64, (Arc<RenderImage>, Shared<Task<Option<LanguageModelImage>>>)>,
 415    image_anchors: Vec<ImageAnchor>,
 416    messages_metadata: HashMap<MessageId, MessageMetadata>,
 417    summary: Option<ContextSummary>,
 418    pending_summary: Task<Option<()>>,
 419    completion_count: usize,
 420    pending_completions: Vec<PendingCompletion>,
 421    token_count: Option<usize>,
 422    pending_token_count: Task<Option<()>>,
 423    pending_save: Task<Result<()>>,
 424    path: Option<PathBuf>,
 425    _subscriptions: Vec<Subscription>,
 426    telemetry: Option<Arc<Telemetry>>,
 427    language_registry: Arc<LanguageRegistry>,
 428    workflow_steps: Vec<WorkflowStepEntry>,
 429    edits_since_last_workflow_step_prune: language::Subscription,
 430    project: Option<Model<Project>>,
 431    prompt_builder: Arc<PromptBuilder>,
 432}
 433
 434impl EventEmitter<ContextEvent> for Context {}
 435
 436impl Context {
 437    pub fn local(
 438        language_registry: Arc<LanguageRegistry>,
 439        project: Option<Model<Project>>,
 440        telemetry: Option<Arc<Telemetry>>,
 441        prompt_builder: Arc<PromptBuilder>,
 442        cx: &mut ModelContext<Self>,
 443    ) -> Self {
 444        Self::new(
 445            ContextId::new(),
 446            ReplicaId::default(),
 447            language::Capability::ReadWrite,
 448            language_registry,
 449            prompt_builder,
 450            project,
 451            telemetry,
 452            cx,
 453        )
 454    }
 455
 456    #[allow(clippy::too_many_arguments)]
 457    pub fn new(
 458        id: ContextId,
 459        replica_id: ReplicaId,
 460        capability: language::Capability,
 461        language_registry: Arc<LanguageRegistry>,
 462        prompt_builder: Arc<PromptBuilder>,
 463        project: Option<Model<Project>>,
 464        telemetry: Option<Arc<Telemetry>>,
 465        cx: &mut ModelContext<Self>,
 466    ) -> Self {
 467        let buffer = cx.new_model(|_cx| {
 468            let mut buffer = Buffer::remote(
 469                language::BufferId::new(1).unwrap(),
 470                replica_id,
 471                capability,
 472                "",
 473            );
 474            buffer.set_language_registry(language_registry.clone());
 475            buffer
 476        });
 477        let edits_since_last_slash_command_parse =
 478            buffer.update(cx, |buffer, _| buffer.subscribe());
 479        let edits_since_last_workflow_step_prune =
 480            buffer.update(cx, |buffer, _| buffer.subscribe());
 481        let mut this = Self {
 482            id,
 483            timestamp: clock::Lamport::new(replica_id),
 484            version: clock::Global::new(),
 485            pending_ops: Vec::new(),
 486            operations: Vec::new(),
 487            message_anchors: Default::default(),
 488            image_anchors: Default::default(),
 489            images: Default::default(),
 490            messages_metadata: Default::default(),
 491            pending_slash_commands: Vec::new(),
 492            finished_slash_commands: HashSet::default(),
 493            slash_command_output_sections: Vec::new(),
 494            edits_since_last_slash_command_parse,
 495            summary: None,
 496            pending_summary: Task::ready(None),
 497            completion_count: Default::default(),
 498            pending_completions: Default::default(),
 499            token_count: None,
 500            pending_token_count: Task::ready(None),
 501            _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
 502            pending_save: Task::ready(Ok(())),
 503            path: None,
 504            buffer,
 505            telemetry,
 506            project,
 507            language_registry,
 508            workflow_steps: Vec::new(),
 509            edits_since_last_workflow_step_prune,
 510            prompt_builder,
 511        };
 512
 513        let first_message_id = MessageId(clock::Lamport {
 514            replica_id: 0,
 515            value: 0,
 516        });
 517        let message = MessageAnchor {
 518            id: first_message_id,
 519            start: language::Anchor::MIN,
 520        };
 521        this.messages_metadata.insert(
 522            first_message_id,
 523            MessageMetadata {
 524                role: Role::User,
 525                status: MessageStatus::Done,
 526                timestamp: first_message_id.0,
 527            },
 528        );
 529        this.message_anchors.push(message);
 530
 531        this.set_language(cx);
 532        this.count_remaining_tokens(cx);
 533        this
 534    }
 535
 536    pub(crate) fn serialize(&self, cx: &AppContext) -> SavedContext {
 537        let buffer = self.buffer.read(cx);
 538        SavedContext {
 539            id: Some(self.id.clone()),
 540            zed: "context".into(),
 541            version: SavedContext::VERSION.into(),
 542            text: buffer.text(),
 543            messages: self
 544                .messages(cx)
 545                .map(|message| SavedMessage {
 546                    id: message.id,
 547                    start: message.offset_range.start,
 548                    metadata: self.messages_metadata[&message.id].clone(),
 549                    image_offsets: message
 550                        .image_offsets
 551                        .iter()
 552                        .map(|image_offset| (image_offset.0, image_offset.1.image_id))
 553                        .collect(),
 554                })
 555                .collect(),
 556            summary: self
 557                .summary
 558                .as_ref()
 559                .map(|summary| summary.text.clone())
 560                .unwrap_or_default(),
 561            slash_command_output_sections: self
 562                .slash_command_output_sections
 563                .iter()
 564                .filter_map(|section| {
 565                    let range = section.range.to_offset(buffer);
 566                    if section.range.start.is_valid(buffer) && !range.is_empty() {
 567                        Some(assistant_slash_command::SlashCommandOutputSection {
 568                            range,
 569                            icon: section.icon,
 570                            label: section.label.clone(),
 571                        })
 572                    } else {
 573                        None
 574                    }
 575                })
 576                .collect(),
 577        }
 578    }
 579
 580    #[allow(clippy::too_many_arguments)]
 581    pub fn deserialize(
 582        saved_context: SavedContext,
 583        path: PathBuf,
 584        language_registry: Arc<LanguageRegistry>,
 585        prompt_builder: Arc<PromptBuilder>,
 586        project: Option<Model<Project>>,
 587        telemetry: Option<Arc<Telemetry>>,
 588        cx: &mut ModelContext<Self>,
 589    ) -> Self {
 590        let id = saved_context.id.clone().unwrap_or_else(|| ContextId::new());
 591        let mut this = Self::new(
 592            id,
 593            ReplicaId::default(),
 594            language::Capability::ReadWrite,
 595            language_registry,
 596            prompt_builder,
 597            project,
 598            telemetry,
 599            cx,
 600        );
 601        this.path = Some(path);
 602        this.buffer.update(cx, |buffer, cx| {
 603            buffer.set_text(saved_context.text.as_str(), cx)
 604        });
 605        let operations = saved_context.into_ops(&this.buffer, cx);
 606        this.apply_ops(operations, cx).unwrap();
 607        this
 608    }
 609
 610    pub fn id(&self) -> &ContextId {
 611        &self.id
 612    }
 613
 614    pub fn replica_id(&self) -> ReplicaId {
 615        self.timestamp.replica_id
 616    }
 617
 618    pub fn version(&self, cx: &AppContext) -> ContextVersion {
 619        ContextVersion {
 620            context: self.version.clone(),
 621            buffer: self.buffer.read(cx).version(),
 622        }
 623    }
 624
 625    pub fn set_capability(
 626        &mut self,
 627        capability: language::Capability,
 628        cx: &mut ModelContext<Self>,
 629    ) {
 630        self.buffer
 631            .update(cx, |buffer, cx| buffer.set_capability(capability, cx));
 632    }
 633
 634    fn next_timestamp(&mut self) -> clock::Lamport {
 635        let timestamp = self.timestamp.tick();
 636        self.version.observe(timestamp);
 637        timestamp
 638    }
 639
 640    pub fn serialize_ops(
 641        &self,
 642        since: &ContextVersion,
 643        cx: &AppContext,
 644    ) -> Task<Vec<proto::ContextOperation>> {
 645        let buffer_ops = self
 646            .buffer
 647            .read(cx)
 648            .serialize_ops(Some(since.buffer.clone()), cx);
 649
 650        let mut context_ops = self
 651            .operations
 652            .iter()
 653            .filter(|op| !since.context.observed(op.timestamp()))
 654            .cloned()
 655            .collect::<Vec<_>>();
 656        context_ops.extend(self.pending_ops.iter().cloned());
 657
 658        cx.background_executor().spawn(async move {
 659            let buffer_ops = buffer_ops.await;
 660            context_ops.sort_unstable_by_key(|op| op.timestamp());
 661            buffer_ops
 662                .into_iter()
 663                .map(|op| proto::ContextOperation {
 664                    variant: Some(proto::context_operation::Variant::BufferOperation(
 665                        proto::context_operation::BufferOperation {
 666                            operation: Some(op),
 667                        },
 668                    )),
 669                })
 670                .chain(context_ops.into_iter().map(|op| op.to_proto()))
 671                .collect()
 672        })
 673    }
 674
 675    pub fn apply_ops(
 676        &mut self,
 677        ops: impl IntoIterator<Item = ContextOperation>,
 678        cx: &mut ModelContext<Self>,
 679    ) -> Result<()> {
 680        let mut buffer_ops = Vec::new();
 681        for op in ops {
 682            match op {
 683                ContextOperation::BufferOperation(buffer_op) => buffer_ops.push(buffer_op),
 684                op @ _ => self.pending_ops.push(op),
 685            }
 686        }
 687        self.buffer
 688            .update(cx, |buffer, cx| buffer.apply_ops(buffer_ops, cx))?;
 689        self.flush_ops(cx);
 690
 691        Ok(())
 692    }
 693
 694    fn flush_ops(&mut self, cx: &mut ModelContext<Context>) {
 695        let mut messages_changed = false;
 696        let mut summary_changed = false;
 697
 698        self.pending_ops.sort_unstable_by_key(|op| op.timestamp());
 699        for op in mem::take(&mut self.pending_ops) {
 700            if !self.can_apply_op(&op, cx) {
 701                self.pending_ops.push(op);
 702                continue;
 703            }
 704
 705            let timestamp = op.timestamp();
 706            match op.clone() {
 707                ContextOperation::InsertMessage {
 708                    anchor, metadata, ..
 709                } => {
 710                    if self.messages_metadata.contains_key(&anchor.id) {
 711                        // We already applied this operation.
 712                    } else {
 713                        self.insert_message(anchor, metadata, cx);
 714                        messages_changed = true;
 715                    }
 716                }
 717                ContextOperation::UpdateMessage {
 718                    message_id,
 719                    metadata: new_metadata,
 720                    ..
 721                } => {
 722                    let metadata = self.messages_metadata.get_mut(&message_id).unwrap();
 723                    if new_metadata.timestamp > metadata.timestamp {
 724                        *metadata = new_metadata;
 725                        messages_changed = true;
 726                    }
 727                }
 728                ContextOperation::UpdateSummary {
 729                    summary: new_summary,
 730                    ..
 731                } => {
 732                    if self
 733                        .summary
 734                        .as_ref()
 735                        .map_or(true, |summary| new_summary.timestamp > summary.timestamp)
 736                    {
 737                        self.summary = Some(new_summary);
 738                        summary_changed = true;
 739                    }
 740                }
 741                ContextOperation::SlashCommandFinished {
 742                    id,
 743                    output_range,
 744                    sections,
 745                    ..
 746                } => {
 747                    if self.finished_slash_commands.insert(id) {
 748                        let buffer = self.buffer.read(cx);
 749                        self.slash_command_output_sections
 750                            .extend(sections.iter().cloned());
 751                        self.slash_command_output_sections
 752                            .sort_by(|a, b| a.range.cmp(&b.range, buffer));
 753                        cx.emit(ContextEvent::SlashCommandFinished {
 754                            output_range,
 755                            sections,
 756                            run_commands_in_output: false,
 757                        });
 758                    }
 759                }
 760                ContextOperation::BufferOperation(_) => unreachable!(),
 761            }
 762
 763            self.version.observe(timestamp);
 764            self.timestamp.observe(timestamp);
 765            self.operations.push(op);
 766        }
 767
 768        if messages_changed {
 769            cx.emit(ContextEvent::MessagesEdited);
 770            cx.notify();
 771        }
 772
 773        if summary_changed {
 774            cx.emit(ContextEvent::SummaryChanged);
 775            cx.notify();
 776        }
 777    }
 778
 779    fn can_apply_op(&self, op: &ContextOperation, cx: &AppContext) -> bool {
 780        if !self.version.observed_all(op.version()) {
 781            return false;
 782        }
 783
 784        match op {
 785            ContextOperation::InsertMessage { anchor, .. } => self
 786                .buffer
 787                .read(cx)
 788                .version
 789                .observed(anchor.start.timestamp),
 790            ContextOperation::UpdateMessage { message_id, .. } => {
 791                self.messages_metadata.contains_key(message_id)
 792            }
 793            ContextOperation::UpdateSummary { .. } => true,
 794            ContextOperation::SlashCommandFinished {
 795                output_range,
 796                sections,
 797                ..
 798            } => {
 799                let version = &self.buffer.read(cx).version;
 800                sections
 801                    .iter()
 802                    .map(|section| &section.range)
 803                    .chain([output_range])
 804                    .all(|range| {
 805                        let observed_start = range.start == language::Anchor::MIN
 806                            || range.start == language::Anchor::MAX
 807                            || version.observed(range.start.timestamp);
 808                        let observed_end = range.end == language::Anchor::MIN
 809                            || range.end == language::Anchor::MAX
 810                            || version.observed(range.end.timestamp);
 811                        observed_start && observed_end
 812                    })
 813            }
 814            ContextOperation::BufferOperation(_) => {
 815                panic!("buffer operations should always be applied")
 816            }
 817        }
 818    }
 819
 820    fn push_op(&mut self, op: ContextOperation, cx: &mut ModelContext<Self>) {
 821        self.operations.push(op.clone());
 822        cx.emit(ContextEvent::Operation(op));
 823    }
 824
 825    pub fn buffer(&self) -> &Model<Buffer> {
 826        &self.buffer
 827    }
 828
 829    pub fn language_registry(&self) -> Arc<LanguageRegistry> {
 830        self.language_registry.clone()
 831    }
 832
 833    pub fn project(&self) -> Option<Model<Project>> {
 834        self.project.clone()
 835    }
 836
 837    pub fn prompt_builder(&self) -> Arc<PromptBuilder> {
 838        self.prompt_builder.clone()
 839    }
 840
 841    pub fn path(&self) -> Option<&Path> {
 842        self.path.as_deref()
 843    }
 844
 845    pub fn summary(&self) -> Option<&ContextSummary> {
 846        self.summary.as_ref()
 847    }
 848
 849    pub fn workflow_step_containing(
 850        &self,
 851        offset: usize,
 852        cx: &AppContext,
 853    ) -> Option<(Range<language::Anchor>, Model<WorkflowStep>)> {
 854        let buffer = self.buffer.read(cx);
 855        let index = self
 856            .workflow_steps
 857            .binary_search_by(|step| {
 858                let step_range = step.range.to_offset(&buffer);
 859                if offset < step_range.start {
 860                    Ordering::Greater
 861                } else if offset > step_range.end {
 862                    Ordering::Less
 863                } else {
 864                    Ordering::Equal
 865                }
 866            })
 867            .ok()?;
 868        let step = &self.workflow_steps[index];
 869        Some((step.range.clone(), step.step.clone()))
 870    }
 871
 872    pub fn workflow_step_for_range(
 873        &self,
 874        range: Range<language::Anchor>,
 875    ) -> Option<Model<WorkflowStep>> {
 876        Some(
 877            self.workflow_steps
 878                .iter()
 879                .find(|step| step.range == range)?
 880                .step
 881                .clone(),
 882        )
 883    }
 884
 885    pub fn pending_slash_commands(&self) -> &[PendingSlashCommand] {
 886        &self.pending_slash_commands
 887    }
 888
 889    pub fn slash_command_output_sections(&self) -> &[SlashCommandOutputSection<language::Anchor>] {
 890        &self.slash_command_output_sections
 891    }
 892
 893    fn set_language(&mut self, cx: &mut ModelContext<Self>) {
 894        let markdown = self.language_registry.language_for_name("Markdown");
 895        cx.spawn(|this, mut cx| async move {
 896            let markdown = markdown.await?;
 897            this.update(&mut cx, |this, cx| {
 898                this.buffer
 899                    .update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx));
 900            })
 901        })
 902        .detach_and_log_err(cx);
 903    }
 904
 905    fn handle_buffer_event(
 906        &mut self,
 907        _: Model<Buffer>,
 908        event: &language::Event,
 909        cx: &mut ModelContext<Self>,
 910    ) {
 911        match event {
 912            language::Event::Operation(operation) => cx.emit(ContextEvent::Operation(
 913                ContextOperation::BufferOperation(operation.clone()),
 914            )),
 915            language::Event::Edited => {
 916                self.count_remaining_tokens(cx);
 917                self.reparse_slash_commands(cx);
 918                // Use `inclusive = true` to invalidate a step when an edit occurs
 919                // at the start/end of a parsed step.
 920                self.prune_invalid_workflow_steps(true, cx);
 921                cx.emit(ContextEvent::MessagesEdited);
 922            }
 923            _ => {}
 924        }
 925    }
 926
 927    pub(crate) fn token_count(&self) -> Option<usize> {
 928        self.token_count
 929    }
 930
 931    pub(crate) fn count_remaining_tokens(&mut self, cx: &mut ModelContext<Self>) {
 932        let request = self.to_completion_request(cx);
 933        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
 934            return;
 935        };
 936        self.pending_token_count = cx.spawn(|this, mut cx| {
 937            async move {
 938                cx.background_executor()
 939                    .timer(Duration::from_millis(200))
 940                    .await;
 941
 942                let token_count = cx.update(|cx| model.count_tokens(request, cx))?.await?;
 943                this.update(&mut cx, |this, cx| {
 944                    this.token_count = Some(token_count);
 945                    cx.notify()
 946                })
 947            }
 948            .log_err()
 949        });
 950    }
 951
 952    pub fn reparse_slash_commands(&mut self, cx: &mut ModelContext<Self>) {
 953        let buffer = self.buffer.read(cx);
 954        let mut row_ranges = self
 955            .edits_since_last_slash_command_parse
 956            .consume()
 957            .into_iter()
 958            .map(|edit| {
 959                let start_row = buffer.offset_to_point(edit.new.start).row;
 960                let end_row = buffer.offset_to_point(edit.new.end).row + 1;
 961                start_row..end_row
 962            })
 963            .peekable();
 964
 965        let mut removed = Vec::new();
 966        let mut updated = Vec::new();
 967        while let Some(mut row_range) = row_ranges.next() {
 968            while let Some(next_row_range) = row_ranges.peek() {
 969                if row_range.end >= next_row_range.start {
 970                    row_range.end = next_row_range.end;
 971                    row_ranges.next();
 972                } else {
 973                    break;
 974                }
 975            }
 976
 977            let start = buffer.anchor_before(Point::new(row_range.start, 0));
 978            let end = buffer.anchor_after(Point::new(
 979                row_range.end - 1,
 980                buffer.line_len(row_range.end - 1),
 981            ));
 982
 983            let old_range = self.pending_command_indices_for_range(start..end, cx);
 984
 985            let mut new_commands = Vec::new();
 986            let mut lines = buffer.text_for_range(start..end).lines();
 987            let mut offset = lines.offset();
 988            while let Some(line) = lines.next() {
 989                if let Some(command_line) = SlashCommandLine::parse(line) {
 990                    let name = &line[command_line.name.clone()];
 991                    let arguments = command_line
 992                        .arguments
 993                        .iter()
 994                        .filter_map(|argument_range| {
 995                            if argument_range.is_empty() {
 996                                None
 997                            } else {
 998                                line.get(argument_range.clone())
 999                            }
1000                        })
1001                        .map(ToOwned::to_owned)
1002                        .collect::<SmallVec<_>>();
1003                    if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1004                        if !command.requires_argument() || !arguments.is_empty() {
1005                            let start_ix = offset + command_line.name.start - 1;
1006                            let end_ix = offset
1007                                + command_line
1008                                    .arguments
1009                                    .last()
1010                                    .map_or(command_line.name.end, |argument| argument.end);
1011                            let source_range =
1012                                buffer.anchor_after(start_ix)..buffer.anchor_after(end_ix);
1013                            let pending_command = PendingSlashCommand {
1014                                name: name.to_string(),
1015                                arguments,
1016                                source_range,
1017                                status: PendingSlashCommandStatus::Idle,
1018                            };
1019                            updated.push(pending_command.clone());
1020                            new_commands.push(pending_command);
1021                        }
1022                    }
1023                }
1024
1025                offset = lines.offset();
1026            }
1027
1028            let removed_commands = self.pending_slash_commands.splice(old_range, new_commands);
1029            removed.extend(removed_commands.map(|command| command.source_range));
1030        }
1031
1032        if !updated.is_empty() || !removed.is_empty() {
1033            cx.emit(ContextEvent::PendingSlashCommandsUpdated { removed, updated });
1034        }
1035    }
1036
1037    fn prune_invalid_workflow_steps(&mut self, inclusive: bool, cx: &mut ModelContext<Self>) {
1038        let mut removed = Vec::new();
1039
1040        for edit_range in self.edits_since_last_workflow_step_prune.consume() {
1041            let intersecting_range = self.find_intersecting_steps(edit_range.new, inclusive, cx);
1042            removed.extend(
1043                self.workflow_steps
1044                    .drain(intersecting_range)
1045                    .map(|step| step.range),
1046            );
1047        }
1048
1049        if !removed.is_empty() {
1050            cx.emit(ContextEvent::WorkflowStepsRemoved(removed));
1051            cx.notify();
1052        }
1053    }
1054
1055    fn find_intersecting_steps(
1056        &self,
1057        range: Range<usize>,
1058        inclusive: bool,
1059        cx: &AppContext,
1060    ) -> Range<usize> {
1061        let buffer = self.buffer.read(cx);
1062        let start_ix = match self.workflow_steps.binary_search_by(|probe| {
1063            probe
1064                .range
1065                .end
1066                .to_offset(buffer)
1067                .cmp(&range.start)
1068                .then(if inclusive {
1069                    Ordering::Greater
1070                } else {
1071                    Ordering::Less
1072                })
1073        }) {
1074            Ok(ix) | Err(ix) => ix,
1075        };
1076        let end_ix = match self.workflow_steps.binary_search_by(|probe| {
1077            probe
1078                .range
1079                .start
1080                .to_offset(buffer)
1081                .cmp(&range.end)
1082                .then(if inclusive {
1083                    Ordering::Less
1084                } else {
1085                    Ordering::Greater
1086                })
1087        }) {
1088            Ok(ix) | Err(ix) => ix,
1089        };
1090        start_ix..end_ix
1091    }
1092
1093    fn parse_workflow_steps_in_range(&mut self, range: Range<usize>, cx: &mut ModelContext<Self>) {
1094        let weak_self = cx.weak_model();
1095        let mut new_edit_steps = Vec::new();
1096        let mut edits = Vec::new();
1097
1098        let buffer = self.buffer.read(cx).snapshot();
1099        let mut message_lines = buffer.as_rope().chunks_in_range(range).lines();
1100        let mut in_step = false;
1101        let mut step_open_tag_start_ix = 0;
1102        let mut line_start_offset = message_lines.offset();
1103
1104        while let Some(line) = message_lines.next() {
1105            if let Some(step_start_index) = line.find("<step>") {
1106                if !in_step {
1107                    in_step = true;
1108                    step_open_tag_start_ix = line_start_offset + step_start_index;
1109                }
1110            }
1111
1112            if let Some(step_end_index) = line.find("</step>") {
1113                if in_step {
1114                    let mut step_open_tag_end_ix = step_open_tag_start_ix + "<step>".len();
1115                    if buffer.chars_at(step_open_tag_end_ix).next() == Some('\n') {
1116                        step_open_tag_end_ix += 1;
1117                    }
1118                    let mut step_end_tag_start_ix = line_start_offset + step_end_index;
1119                    let step_end_tag_end_ix = step_end_tag_start_ix + "</step>".len();
1120                    if buffer.reversed_chars_at(step_end_tag_start_ix).next() == Some('\n') {
1121                        step_end_tag_start_ix -= 1;
1122                    }
1123                    edits.push((step_open_tag_start_ix..step_open_tag_end_ix, ""));
1124                    edits.push((step_end_tag_start_ix..step_end_tag_end_ix, ""));
1125                    let tagged_range = buffer.anchor_after(step_open_tag_end_ix)
1126                        ..buffer.anchor_before(step_end_tag_start_ix);
1127
1128                    // Check if a step with the same range already exists
1129                    let existing_step_index = self
1130                        .workflow_steps
1131                        .binary_search_by(|probe| probe.range.cmp(&tagged_range, &buffer));
1132
1133                    if let Err(ix) = existing_step_index {
1134                        new_edit_steps.push((
1135                            ix,
1136                            WorkflowStepEntry {
1137                                step: cx.new_model(|_| {
1138                                    WorkflowStep::new(tagged_range.clone(), weak_self.clone())
1139                                }),
1140                                range: tagged_range,
1141                            },
1142                        ));
1143                    }
1144
1145                    in_step = false;
1146                }
1147            }
1148
1149            line_start_offset = message_lines.offset();
1150        }
1151
1152        let mut updated = Vec::new();
1153        for (index, step) in new_edit_steps.into_iter().rev() {
1154            let step_range = step.range.clone();
1155            updated.push(step_range.clone());
1156            self.workflow_steps.insert(index, step);
1157            self.resolve_workflow_step(step_range, cx);
1158        }
1159
1160        // Delete <step> tags, making sure we don't accidentally invalidate
1161        // the step we just parsed.
1162        self.buffer
1163            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
1164        self.edits_since_last_workflow_step_prune.consume();
1165    }
1166
1167    pub fn resolve_workflow_step(
1168        &mut self,
1169        tagged_range: Range<language::Anchor>,
1170        cx: &mut ModelContext<Self>,
1171    ) {
1172        let Ok(step_index) = self
1173            .workflow_steps
1174            .binary_search_by(|step| step.range.cmp(&tagged_range, self.buffer.read(cx)))
1175        else {
1176            return;
1177        };
1178
1179        cx.emit(ContextEvent::WorkflowStepUpdated(tagged_range.clone()));
1180        cx.notify();
1181
1182        let resolution = self.workflow_steps[step_index].step.clone();
1183        cx.defer(move |cx| {
1184            resolution.update(cx, |resolution, cx| resolution.resolve(cx));
1185        });
1186    }
1187
1188    pub fn workflow_step_updated(
1189        &mut self,
1190        range: Range<language::Anchor>,
1191        cx: &mut ModelContext<Self>,
1192    ) {
1193        cx.emit(ContextEvent::WorkflowStepUpdated(range));
1194        cx.notify();
1195    }
1196
1197    pub fn pending_command_for_position(
1198        &mut self,
1199        position: language::Anchor,
1200        cx: &mut ModelContext<Self>,
1201    ) -> Option<&mut PendingSlashCommand> {
1202        let buffer = self.buffer.read(cx);
1203        match self
1204            .pending_slash_commands
1205            .binary_search_by(|probe| probe.source_range.end.cmp(&position, buffer))
1206        {
1207            Ok(ix) => Some(&mut self.pending_slash_commands[ix]),
1208            Err(ix) => {
1209                let cmd = self.pending_slash_commands.get_mut(ix)?;
1210                if position.cmp(&cmd.source_range.start, buffer).is_ge()
1211                    && position.cmp(&cmd.source_range.end, buffer).is_le()
1212                {
1213                    Some(cmd)
1214                } else {
1215                    None
1216                }
1217            }
1218        }
1219    }
1220
1221    pub fn pending_commands_for_range(
1222        &self,
1223        range: Range<language::Anchor>,
1224        cx: &AppContext,
1225    ) -> &[PendingSlashCommand] {
1226        let range = self.pending_command_indices_for_range(range, cx);
1227        &self.pending_slash_commands[range]
1228    }
1229
1230    fn pending_command_indices_for_range(
1231        &self,
1232        range: Range<language::Anchor>,
1233        cx: &AppContext,
1234    ) -> Range<usize> {
1235        let buffer = self.buffer.read(cx);
1236        let start_ix = match self
1237            .pending_slash_commands
1238            .binary_search_by(|probe| probe.source_range.end.cmp(&range.start, &buffer))
1239        {
1240            Ok(ix) | Err(ix) => ix,
1241        };
1242        let end_ix = match self
1243            .pending_slash_commands
1244            .binary_search_by(|probe| probe.source_range.start.cmp(&range.end, &buffer))
1245        {
1246            Ok(ix) => ix + 1,
1247            Err(ix) => ix,
1248        };
1249        start_ix..end_ix
1250    }
1251
1252    pub fn insert_command_output(
1253        &mut self,
1254        command_range: Range<language::Anchor>,
1255        output: Task<Result<SlashCommandOutput>>,
1256        insert_trailing_newline: bool,
1257        cx: &mut ModelContext<Self>,
1258    ) {
1259        self.reparse_slash_commands(cx);
1260
1261        let insert_output_task = cx.spawn(|this, mut cx| {
1262            let command_range = command_range.clone();
1263            async move {
1264                let output = output.await;
1265                this.update(&mut cx, |this, cx| match output {
1266                    Ok(mut output) => {
1267                        if insert_trailing_newline {
1268                            output.text.push('\n');
1269                        }
1270
1271                        let version = this.version.clone();
1272                        let command_id = SlashCommandId(this.next_timestamp());
1273                        let (operation, event) = this.buffer.update(cx, |buffer, cx| {
1274                            let start = command_range.start.to_offset(buffer);
1275                            let old_end = command_range.end.to_offset(buffer);
1276                            let new_end = start + output.text.len();
1277                            buffer.edit([(start..old_end, output.text)], None, cx);
1278
1279                            let mut sections = output
1280                                .sections
1281                                .into_iter()
1282                                .map(|section| SlashCommandOutputSection {
1283                                    range: buffer.anchor_after(start + section.range.start)
1284                                        ..buffer.anchor_before(start + section.range.end),
1285                                    icon: section.icon,
1286                                    label: section.label,
1287                                })
1288                                .collect::<Vec<_>>();
1289                            sections.sort_by(|a, b| a.range.cmp(&b.range, buffer));
1290
1291                            this.slash_command_output_sections
1292                                .extend(sections.iter().cloned());
1293                            this.slash_command_output_sections
1294                                .sort_by(|a, b| a.range.cmp(&b.range, buffer));
1295
1296                            let output_range =
1297                                buffer.anchor_after(start)..buffer.anchor_before(new_end);
1298                            this.finished_slash_commands.insert(command_id);
1299
1300                            (
1301                                ContextOperation::SlashCommandFinished {
1302                                    id: command_id,
1303                                    output_range: output_range.clone(),
1304                                    sections: sections.clone(),
1305                                    version,
1306                                },
1307                                ContextEvent::SlashCommandFinished {
1308                                    output_range,
1309                                    sections,
1310                                    run_commands_in_output: output.run_commands_in_text,
1311                                },
1312                            )
1313                        });
1314
1315                        this.push_op(operation, cx);
1316                        cx.emit(event);
1317                    }
1318                    Err(error) => {
1319                        if let Some(pending_command) =
1320                            this.pending_command_for_position(command_range.start, cx)
1321                        {
1322                            pending_command.status =
1323                                PendingSlashCommandStatus::Error(error.to_string());
1324                            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1325                                removed: vec![pending_command.source_range.clone()],
1326                                updated: vec![pending_command.clone()],
1327                            });
1328                        }
1329                    }
1330                })
1331                .ok();
1332            }
1333        });
1334
1335        if let Some(pending_command) = self.pending_command_for_position(command_range.start, cx) {
1336            pending_command.status = PendingSlashCommandStatus::Running {
1337                _task: insert_output_task.shared(),
1338            };
1339            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1340                removed: vec![pending_command.source_range.clone()],
1341                updated: vec![pending_command.clone()],
1342            });
1343        }
1344    }
1345
1346    pub fn completion_provider_changed(&mut self, cx: &mut ModelContext<Self>) {
1347        self.count_remaining_tokens(cx);
1348    }
1349
1350    pub fn assist(&mut self, cx: &mut ModelContext<Self>) -> Option<MessageAnchor> {
1351        let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
1352        let model = LanguageModelRegistry::read_global(cx).active_model()?;
1353        let last_message_id = self.message_anchors.iter().rev().find_map(|message| {
1354            message
1355                .start
1356                .is_valid(self.buffer.read(cx))
1357                .then_some(message.id)
1358        })?;
1359
1360        if !provider.is_authenticated(cx) {
1361            log::info!("completion provider has no credentials");
1362            return None;
1363        }
1364
1365        let request = self.to_completion_request(cx);
1366        let assistant_message = self
1367            .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1368            .unwrap();
1369
1370        // Queue up the user's next reply.
1371        let user_message = self
1372            .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
1373            .unwrap();
1374
1375        let pending_completion_id = post_inc(&mut self.completion_count);
1376
1377        let task = cx.spawn({
1378            |this, mut cx| async move {
1379                let stream = model.stream_completion(request, &cx);
1380                let assistant_message_id = assistant_message.id;
1381                let mut response_latency = None;
1382                let stream_completion = async {
1383                    let request_start = Instant::now();
1384                    let mut chunks = stream.await?;
1385
1386                    while let Some(chunk) = chunks.next().await {
1387                        if response_latency.is_none() {
1388                            response_latency = Some(request_start.elapsed());
1389                        }
1390                        let chunk = chunk?;
1391
1392                        this.update(&mut cx, |this, cx| {
1393                            let message_ix = this
1394                                .message_anchors
1395                                .iter()
1396                                .position(|message| message.id == assistant_message_id)?;
1397                            let message_range = this.buffer.update(cx, |buffer, cx| {
1398                                let message_start_offset =
1399                                    this.message_anchors[message_ix].start.to_offset(buffer);
1400                                let message_old_end_offset = this.message_anchors[message_ix + 1..]
1401                                    .iter()
1402                                    .find(|message| message.start.is_valid(buffer))
1403                                    .map_or(buffer.len(), |message| {
1404                                        message.start.to_offset(buffer).saturating_sub(1)
1405                                    });
1406                                let message_new_end_offset = message_old_end_offset + chunk.len();
1407                                buffer.edit(
1408                                    [(message_old_end_offset..message_old_end_offset, chunk)],
1409                                    None,
1410                                    cx,
1411                                );
1412                                message_start_offset..message_new_end_offset
1413                            });
1414
1415                            // Use `inclusive = false` as edits might occur at the end of a parsed step.
1416                            this.prune_invalid_workflow_steps(false, cx);
1417                            this.parse_workflow_steps_in_range(message_range, cx);
1418                            cx.emit(ContextEvent::StreamedCompletion);
1419
1420                            Some(())
1421                        })?;
1422                        smol::future::yield_now().await;
1423                    }
1424                    this.update(&mut cx, |this, cx| {
1425                        this.pending_completions
1426                            .retain(|completion| completion.id != pending_completion_id);
1427                        this.summarize(false, cx);
1428                    })?;
1429
1430                    anyhow::Ok(())
1431                };
1432
1433                let result = stream_completion.await;
1434
1435                this.update(&mut cx, |this, cx| {
1436                    let error_message = result
1437                        .err()
1438                        .map(|error| error.to_string().trim().to_string());
1439
1440                    if let Some(error_message) = error_message.as_ref() {
1441                        cx.emit(ContextEvent::ShowAssistError(SharedString::from(
1442                            error_message.clone(),
1443                        )));
1444                    }
1445
1446                    this.update_metadata(assistant_message_id, cx, |metadata| {
1447                        if let Some(error_message) = error_message.as_ref() {
1448                            metadata.status =
1449                                MessageStatus::Error(SharedString::from(error_message.clone()));
1450                        } else {
1451                            metadata.status = MessageStatus::Done;
1452                        }
1453                    });
1454
1455                    if let Some(telemetry) = this.telemetry.as_ref() {
1456                        telemetry.report_assistant_event(
1457                            Some(this.id.0.clone()),
1458                            AssistantKind::Panel,
1459                            model.telemetry_id(),
1460                            response_latency,
1461                            error_message,
1462                        );
1463                    }
1464                })
1465                .ok();
1466            }
1467        });
1468
1469        self.pending_completions.push(PendingCompletion {
1470            id: pending_completion_id,
1471            assistant_message_id: assistant_message.id,
1472            _task: task,
1473        });
1474
1475        Some(user_message)
1476    }
1477
1478    pub fn to_completion_request(&self, cx: &AppContext) -> LanguageModelRequest {
1479        let buffer = self.buffer.read(cx);
1480        let request_messages = self
1481            .messages(cx)
1482            .filter(|message| message.status == MessageStatus::Done)
1483            .map(|message| message.to_request_message(&buffer))
1484            .collect();
1485
1486        LanguageModelRequest {
1487            messages: request_messages,
1488            stop: vec![],
1489            temperature: 1.0,
1490        }
1491    }
1492
1493    pub fn cancel_last_assist(&mut self, cx: &mut ModelContext<Self>) -> bool {
1494        if let Some(pending_completion) = self.pending_completions.pop() {
1495            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
1496                if metadata.status == MessageStatus::Pending {
1497                    metadata.status = MessageStatus::Canceled;
1498                }
1499            });
1500            true
1501        } else {
1502            false
1503        }
1504    }
1505
1506    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
1507        for id in ids {
1508            if let Some(metadata) = self.messages_metadata.get(&id) {
1509                let role = metadata.role.cycle();
1510                self.update_metadata(id, cx, |metadata| metadata.role = role);
1511            }
1512        }
1513    }
1514
1515    pub fn update_metadata(
1516        &mut self,
1517        id: MessageId,
1518        cx: &mut ModelContext<Self>,
1519        f: impl FnOnce(&mut MessageMetadata),
1520    ) {
1521        let version = self.version.clone();
1522        let timestamp = self.next_timestamp();
1523        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
1524            f(metadata);
1525            metadata.timestamp = timestamp;
1526            let operation = ContextOperation::UpdateMessage {
1527                message_id: id,
1528                metadata: metadata.clone(),
1529                version,
1530            };
1531            self.push_op(operation, cx);
1532            cx.emit(ContextEvent::MessagesEdited);
1533            cx.notify();
1534        }
1535    }
1536
1537    pub fn insert_message_after(
1538        &mut self,
1539        message_id: MessageId,
1540        role: Role,
1541        status: MessageStatus,
1542        cx: &mut ModelContext<Self>,
1543    ) -> Option<MessageAnchor> {
1544        if let Some(prev_message_ix) = self
1545            .message_anchors
1546            .iter()
1547            .position(|message| message.id == message_id)
1548        {
1549            // Find the next valid message after the one we were given.
1550            let mut next_message_ix = prev_message_ix + 1;
1551            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
1552                if next_message.start.is_valid(self.buffer.read(cx)) {
1553                    break;
1554                }
1555                next_message_ix += 1;
1556            }
1557
1558            let start = self.buffer.update(cx, |buffer, cx| {
1559                let offset = self
1560                    .message_anchors
1561                    .get(next_message_ix)
1562                    .map_or(buffer.len(), |message| {
1563                        buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
1564                    });
1565                buffer.edit([(offset..offset, "\n")], None, cx);
1566                buffer.anchor_before(offset + 1)
1567            });
1568
1569            let version = self.version.clone();
1570            let anchor = MessageAnchor {
1571                id: MessageId(self.next_timestamp()),
1572                start,
1573            };
1574            let metadata = MessageMetadata {
1575                role,
1576                status,
1577                timestamp: anchor.id.0,
1578            };
1579            self.insert_message(anchor.clone(), metadata.clone(), cx);
1580            self.push_op(
1581                ContextOperation::InsertMessage {
1582                    anchor: anchor.clone(),
1583                    metadata,
1584                    version,
1585                },
1586                cx,
1587            );
1588            Some(anchor)
1589        } else {
1590            None
1591        }
1592    }
1593
1594    pub fn insert_image(&mut self, image: Image, cx: &mut ModelContext<Self>) -> Option<()> {
1595        if let hash_map::Entry::Vacant(entry) = self.images.entry(image.id()) {
1596            entry.insert((
1597                image.to_image_data(cx).log_err()?,
1598                LanguageModelImage::from_image(image, cx).shared(),
1599            ));
1600        }
1601
1602        Some(())
1603    }
1604
1605    pub fn insert_image_anchor(
1606        &mut self,
1607        image_id: u64,
1608        anchor: language::Anchor,
1609        cx: &mut ModelContext<Self>,
1610    ) -> bool {
1611        cx.emit(ContextEvent::MessagesEdited);
1612
1613        let buffer = self.buffer.read(cx);
1614        let insertion_ix = match self
1615            .image_anchors
1616            .binary_search_by(|existing_anchor| anchor.cmp(&existing_anchor.anchor, buffer))
1617        {
1618            Ok(ix) => ix,
1619            Err(ix) => ix,
1620        };
1621
1622        if let Some((render_image, image)) = self.images.get(&image_id) {
1623            self.image_anchors.insert(
1624                insertion_ix,
1625                ImageAnchor {
1626                    anchor,
1627                    image_id,
1628                    image: image.clone(),
1629                    render_image: render_image.clone(),
1630                },
1631            );
1632
1633            true
1634        } else {
1635            false
1636        }
1637    }
1638
1639    pub fn images<'a>(&'a self, _cx: &'a AppContext) -> impl 'a + Iterator<Item = ImageAnchor> {
1640        self.image_anchors.iter().cloned()
1641    }
1642
1643    pub fn split_message(
1644        &mut self,
1645        range: Range<usize>,
1646        cx: &mut ModelContext<Self>,
1647    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
1648        let start_message = self.message_for_offset(range.start, cx);
1649        let end_message = self.message_for_offset(range.end, cx);
1650        if let Some((start_message, end_message)) = start_message.zip(end_message) {
1651            // Prevent splitting when range spans multiple messages.
1652            if start_message.id != end_message.id {
1653                return (None, None);
1654            }
1655
1656            let message = start_message;
1657            let role = message.role;
1658            let mut edited_buffer = false;
1659
1660            let mut suffix_start = None;
1661
1662            // TODO: why did this start panicking?
1663            if range.start > message.offset_range.start
1664                && range.end < message.offset_range.end.saturating_sub(1)
1665            {
1666                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
1667                    suffix_start = Some(range.end + 1);
1668                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
1669                    suffix_start = Some(range.end);
1670                }
1671            }
1672
1673            let version = self.version.clone();
1674            let suffix = if let Some(suffix_start) = suffix_start {
1675                MessageAnchor {
1676                    id: MessageId(self.next_timestamp()),
1677                    start: self.buffer.read(cx).anchor_before(suffix_start),
1678                }
1679            } else {
1680                self.buffer.update(cx, |buffer, cx| {
1681                    buffer.edit([(range.end..range.end, "\n")], None, cx);
1682                });
1683                edited_buffer = true;
1684                MessageAnchor {
1685                    id: MessageId(self.next_timestamp()),
1686                    start: self.buffer.read(cx).anchor_before(range.end + 1),
1687                }
1688            };
1689
1690            let suffix_metadata = MessageMetadata {
1691                role,
1692                status: MessageStatus::Done,
1693                timestamp: suffix.id.0,
1694            };
1695            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
1696            self.push_op(
1697                ContextOperation::InsertMessage {
1698                    anchor: suffix.clone(),
1699                    metadata: suffix_metadata,
1700                    version,
1701                },
1702                cx,
1703            );
1704
1705            let new_messages =
1706                if range.start == range.end || range.start == message.offset_range.start {
1707                    (None, Some(suffix))
1708                } else {
1709                    let mut prefix_end = None;
1710                    if range.start > message.offset_range.start
1711                        && range.end < message.offset_range.end - 1
1712                    {
1713                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
1714                            prefix_end = Some(range.start + 1);
1715                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
1716                            == Some('\n')
1717                        {
1718                            prefix_end = Some(range.start);
1719                        }
1720                    }
1721
1722                    let version = self.version.clone();
1723                    let selection = if let Some(prefix_end) = prefix_end {
1724                        MessageAnchor {
1725                            id: MessageId(self.next_timestamp()),
1726                            start: self.buffer.read(cx).anchor_before(prefix_end),
1727                        }
1728                    } else {
1729                        self.buffer.update(cx, |buffer, cx| {
1730                            buffer.edit([(range.start..range.start, "\n")], None, cx)
1731                        });
1732                        edited_buffer = true;
1733                        MessageAnchor {
1734                            id: MessageId(self.next_timestamp()),
1735                            start: self.buffer.read(cx).anchor_before(range.end + 1),
1736                        }
1737                    };
1738
1739                    let selection_metadata = MessageMetadata {
1740                        role,
1741                        status: MessageStatus::Done,
1742                        timestamp: selection.id.0,
1743                    };
1744                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
1745                    self.push_op(
1746                        ContextOperation::InsertMessage {
1747                            anchor: selection.clone(),
1748                            metadata: selection_metadata,
1749                            version,
1750                        },
1751                        cx,
1752                    );
1753
1754                    (Some(selection), Some(suffix))
1755                };
1756
1757            if !edited_buffer {
1758                cx.emit(ContextEvent::MessagesEdited);
1759            }
1760            new_messages
1761        } else {
1762            (None, None)
1763        }
1764    }
1765
1766    fn insert_message(
1767        &mut self,
1768        new_anchor: MessageAnchor,
1769        new_metadata: MessageMetadata,
1770        cx: &mut ModelContext<Self>,
1771    ) {
1772        cx.emit(ContextEvent::MessagesEdited);
1773
1774        self.messages_metadata.insert(new_anchor.id, new_metadata);
1775
1776        let buffer = self.buffer.read(cx);
1777        let insertion_ix = self
1778            .message_anchors
1779            .iter()
1780            .position(|anchor| {
1781                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
1782                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
1783            })
1784            .unwrap_or(self.message_anchors.len());
1785        self.message_anchors.insert(insertion_ix, new_anchor);
1786    }
1787
1788    pub(super) fn summarize(&mut self, replace_old: bool, cx: &mut ModelContext<Self>) {
1789        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1790            return;
1791        };
1792        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1793            return;
1794        };
1795
1796        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
1797            if !provider.is_authenticated(cx) {
1798                return;
1799            }
1800
1801            let messages = self
1802                .messages(cx)
1803                .map(|message| message.to_request_message(self.buffer.read(cx)))
1804                .chain(Some(LanguageModelRequestMessage {
1805                    role: Role::User,
1806                    content: vec![
1807                        "Summarize the context into a short title without punctuation.".into(),
1808                    ],
1809                }));
1810            let request = LanguageModelRequest {
1811                messages: messages.collect(),
1812                stop: vec![],
1813                temperature: 1.0,
1814            };
1815
1816            self.pending_summary = cx.spawn(|this, mut cx| {
1817                async move {
1818                    let stream = model.stream_completion(request, &cx);
1819                    let mut messages = stream.await?;
1820
1821                    let mut replaced = !replace_old;
1822                    while let Some(message) = messages.next().await {
1823                        let text = message?;
1824                        let mut lines = text.lines();
1825                        this.update(&mut cx, |this, cx| {
1826                            let version = this.version.clone();
1827                            let timestamp = this.next_timestamp();
1828                            let summary = this.summary.get_or_insert(ContextSummary::default());
1829                            if !replaced && replace_old {
1830                                summary.text.clear();
1831                                replaced = true;
1832                            }
1833                            summary.text.extend(lines.next());
1834                            summary.timestamp = timestamp;
1835                            let operation = ContextOperation::UpdateSummary {
1836                                summary: summary.clone(),
1837                                version,
1838                            };
1839                            this.push_op(operation, cx);
1840                            cx.emit(ContextEvent::SummaryChanged);
1841                        })?;
1842
1843                        // Stop if the LLM generated multiple lines.
1844                        if lines.next().is_some() {
1845                            break;
1846                        }
1847                    }
1848
1849                    this.update(&mut cx, |this, cx| {
1850                        let version = this.version.clone();
1851                        let timestamp = this.next_timestamp();
1852                        if let Some(summary) = this.summary.as_mut() {
1853                            summary.done = true;
1854                            summary.timestamp = timestamp;
1855                            let operation = ContextOperation::UpdateSummary {
1856                                summary: summary.clone(),
1857                                version,
1858                            };
1859                            this.push_op(operation, cx);
1860                            cx.emit(ContextEvent::SummaryChanged);
1861                        }
1862                    })?;
1863
1864                    anyhow::Ok(())
1865                }
1866                .log_err()
1867            });
1868        }
1869    }
1870
1871    fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
1872        self.messages_for_offsets([offset], cx).pop()
1873    }
1874
1875    pub fn messages_for_offsets(
1876        &self,
1877        offsets: impl IntoIterator<Item = usize>,
1878        cx: &AppContext,
1879    ) -> Vec<Message> {
1880        let mut result = Vec::new();
1881
1882        let mut messages = self.messages(cx).peekable();
1883        let mut offsets = offsets.into_iter().peekable();
1884        let mut current_message = messages.next();
1885        while let Some(offset) = offsets.next() {
1886            // Locate the message that contains the offset.
1887            while current_message.as_ref().map_or(false, |message| {
1888                !message.offset_range.contains(&offset) && messages.peek().is_some()
1889            }) {
1890                current_message = messages.next();
1891            }
1892            let Some(message) = current_message.as_ref() else {
1893                break;
1894            };
1895
1896            // Skip offsets that are in the same message.
1897            while offsets.peek().map_or(false, |offset| {
1898                message.offset_range.contains(offset) || messages.peek().is_none()
1899            }) {
1900                offsets.next();
1901            }
1902
1903            result.push(message.clone());
1904        }
1905        result
1906    }
1907
1908    pub fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
1909        let buffer = self.buffer.read(cx);
1910        let messages = self.message_anchors.iter().enumerate();
1911        let images = self.image_anchors.iter();
1912
1913        Self::messages_from_iters(buffer, &self.messages_metadata, messages, images)
1914    }
1915
1916    pub fn messages_from_iters<'a>(
1917        buffer: &'a Buffer,
1918        metadata: &'a HashMap<MessageId, MessageMetadata>,
1919        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
1920        images: impl Iterator<Item = &'a ImageAnchor> + 'a,
1921    ) -> impl 'a + Iterator<Item = Message> {
1922        let mut messages = messages.peekable();
1923        let mut images = images.peekable();
1924
1925        iter::from_fn(move || {
1926            if let Some((start_ix, message_anchor)) = messages.next() {
1927                let metadata = metadata.get(&message_anchor.id)?;
1928
1929                let message_start = message_anchor.start.to_offset(buffer);
1930                let mut message_end = None;
1931                let mut end_ix = start_ix;
1932                while let Some((_, next_message)) = messages.peek() {
1933                    if next_message.start.is_valid(buffer) {
1934                        message_end = Some(next_message.start);
1935                        break;
1936                    } else {
1937                        end_ix += 1;
1938                        messages.next();
1939                    }
1940                }
1941                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
1942                let message_end = message_end_anchor.to_offset(buffer);
1943
1944                let mut image_offsets = SmallVec::new();
1945                while let Some(image_anchor) = images.peek() {
1946                    if image_anchor.anchor.cmp(&message_end_anchor, buffer).is_lt() {
1947                        image_offsets.push((
1948                            image_anchor.anchor.to_offset(buffer),
1949                            MessageImage {
1950                                image_id: image_anchor.image_id,
1951                                image: image_anchor.image.clone(),
1952                            },
1953                        ));
1954                        images.next();
1955                    } else {
1956                        break;
1957                    }
1958                }
1959
1960                return Some(Message {
1961                    index_range: start_ix..end_ix,
1962                    offset_range: message_start..message_end,
1963                    id: message_anchor.id,
1964                    anchor: message_anchor.start,
1965                    role: metadata.role,
1966                    status: metadata.status.clone(),
1967                    image_offsets,
1968                });
1969            }
1970            None
1971        })
1972    }
1973
1974    pub fn save(
1975        &mut self,
1976        debounce: Option<Duration>,
1977        fs: Arc<dyn Fs>,
1978        cx: &mut ModelContext<Context>,
1979    ) {
1980        if self.replica_id() != ReplicaId::default() {
1981            // Prevent saving a remote context for now.
1982            return;
1983        }
1984
1985        self.pending_save = cx.spawn(|this, mut cx| async move {
1986            if let Some(debounce) = debounce {
1987                cx.background_executor().timer(debounce).await;
1988            }
1989
1990            let (old_path, summary) = this.read_with(&cx, |this, _| {
1991                let path = this.path.clone();
1992                let summary = if let Some(summary) = this.summary.as_ref() {
1993                    if summary.done {
1994                        Some(summary.text.clone())
1995                    } else {
1996                        None
1997                    }
1998                } else {
1999                    None
2000                };
2001                (path, summary)
2002            })?;
2003
2004            if let Some(summary) = summary {
2005                this.read_with(&cx, |this, cx| this.serialize_images(fs.clone(), cx))?
2006                    .await;
2007
2008                let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2009                let mut discriminant = 1;
2010                let mut new_path;
2011                loop {
2012                    new_path = contexts_dir().join(&format!(
2013                        "{} - {}.zed.json",
2014                        summary.trim(),
2015                        discriminant
2016                    ));
2017                    if fs.is_file(&new_path).await {
2018                        discriminant += 1;
2019                    } else {
2020                        break;
2021                    }
2022                }
2023
2024                fs.create_dir(contexts_dir().as_ref()).await?;
2025                fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
2026                    .await?;
2027                if let Some(old_path) = old_path {
2028                    if new_path != old_path {
2029                        fs.remove_file(
2030                            &old_path,
2031                            RemoveOptions {
2032                                recursive: false,
2033                                ignore_if_not_exists: true,
2034                            },
2035                        )
2036                        .await?;
2037                    }
2038                }
2039
2040                this.update(&mut cx, |this, _| this.path = Some(new_path))?;
2041            }
2042
2043            Ok(())
2044        });
2045    }
2046
2047    pub fn serialize_images(&self, fs: Arc<dyn Fs>, cx: &AppContext) -> Task<()> {
2048        let mut images_to_save = self
2049            .images
2050            .iter()
2051            .map(|(id, (_, llm_image))| {
2052                let fs = fs.clone();
2053                let llm_image = llm_image.clone();
2054                let id = *id;
2055                async move {
2056                    if let Some(llm_image) = llm_image.await {
2057                        let path: PathBuf =
2058                            context_images_dir().join(&format!("{}.png.base64", id));
2059                        if fs
2060                            .metadata(path.as_path())
2061                            .await
2062                            .log_err()
2063                            .flatten()
2064                            .is_none()
2065                        {
2066                            fs.atomic_write(path, llm_image.source.to_string())
2067                                .await
2068                                .log_err();
2069                        }
2070                    }
2071                }
2072            })
2073            .collect::<FuturesUnordered<_>>();
2074        cx.background_executor().spawn(async move {
2075            if fs
2076                .create_dir(context_images_dir().as_ref())
2077                .await
2078                .log_err()
2079                .is_some()
2080            {
2081                while let Some(_) = images_to_save.next().await {}
2082            }
2083        })
2084    }
2085
2086    pub(crate) fn custom_summary(&mut self, custom_summary: String, cx: &mut ModelContext<Self>) {
2087        let timestamp = self.next_timestamp();
2088        let summary = self.summary.get_or_insert(ContextSummary::default());
2089        summary.timestamp = timestamp;
2090        summary.done = true;
2091        summary.text = custom_summary;
2092        cx.emit(ContextEvent::SummaryChanged);
2093    }
2094}
2095
2096#[derive(Debug, Default)]
2097pub struct ContextVersion {
2098    context: clock::Global,
2099    buffer: clock::Global,
2100}
2101
2102impl ContextVersion {
2103    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2104        Self {
2105            context: language::proto::deserialize_version(&proto.context_version),
2106            buffer: language::proto::deserialize_version(&proto.buffer_version),
2107        }
2108    }
2109
2110    pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
2111        proto::ContextVersion {
2112            context_id: context_id.to_proto(),
2113            context_version: language::proto::serialize_version(&self.context),
2114            buffer_version: language::proto::serialize_version(&self.buffer),
2115        }
2116    }
2117}
2118
2119#[derive(Debug, Clone)]
2120pub struct PendingSlashCommand {
2121    pub name: String,
2122    pub arguments: SmallVec<[String; 3]>,
2123    pub status: PendingSlashCommandStatus,
2124    pub source_range: Range<language::Anchor>,
2125}
2126
2127#[derive(Debug, Clone)]
2128pub enum PendingSlashCommandStatus {
2129    Idle,
2130    Running { _task: Shared<Task<()>> },
2131    Error(String),
2132}
2133
2134#[derive(Serialize, Deserialize)]
2135pub struct SavedMessage {
2136    pub id: MessageId,
2137    pub start: usize,
2138    pub metadata: MessageMetadata,
2139    #[serde(default)]
2140    // This is defaulted for backwards compatibility with JSON files created before August 2024. We didn't always have this field.
2141    pub image_offsets: Vec<(usize, u64)>,
2142}
2143
2144#[derive(Serialize, Deserialize)]
2145pub struct SavedContext {
2146    pub id: Option<ContextId>,
2147    pub zed: String,
2148    pub version: String,
2149    pub text: String,
2150    pub messages: Vec<SavedMessage>,
2151    pub summary: String,
2152    pub slash_command_output_sections:
2153        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2154}
2155
2156impl SavedContext {
2157    pub const VERSION: &'static str = "0.4.0";
2158
2159    pub fn from_json(json: &str) -> Result<Self> {
2160        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
2161        match saved_context_json
2162            .get("version")
2163            .ok_or_else(|| anyhow!("version not found"))?
2164        {
2165            serde_json::Value::String(version) => match version.as_str() {
2166                SavedContext::VERSION => {
2167                    Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
2168                }
2169                SavedContextV0_3_0::VERSION => {
2170                    let saved_context =
2171                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
2172                    Ok(saved_context.upgrade())
2173                }
2174                SavedContextV0_2_0::VERSION => {
2175                    let saved_context =
2176                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
2177                    Ok(saved_context.upgrade())
2178                }
2179                SavedContextV0_1_0::VERSION => {
2180                    let saved_context =
2181                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
2182                    Ok(saved_context.upgrade())
2183                }
2184                _ => Err(anyhow!("unrecognized saved context version: {}", version)),
2185            },
2186            _ => Err(anyhow!("version not found on saved context")),
2187        }
2188    }
2189
2190    fn into_ops(
2191        self,
2192        buffer: &Model<Buffer>,
2193        cx: &mut ModelContext<Context>,
2194    ) -> Vec<ContextOperation> {
2195        let mut operations = Vec::new();
2196        let mut version = clock::Global::new();
2197        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
2198
2199        let mut first_message_metadata = None;
2200        for message in self.messages {
2201            if message.id == MessageId(clock::Lamport::default()) {
2202                first_message_metadata = Some(message.metadata);
2203            } else {
2204                operations.push(ContextOperation::InsertMessage {
2205                    anchor: MessageAnchor {
2206                        id: message.id,
2207                        start: buffer.read(cx).anchor_before(message.start),
2208                    },
2209                    metadata: MessageMetadata {
2210                        role: message.metadata.role,
2211                        status: message.metadata.status,
2212                        timestamp: message.metadata.timestamp,
2213                    },
2214                    version: version.clone(),
2215                });
2216                version.observe(message.id.0);
2217                next_timestamp.observe(message.id.0);
2218            }
2219        }
2220
2221        if let Some(metadata) = first_message_metadata {
2222            let timestamp = next_timestamp.tick();
2223            operations.push(ContextOperation::UpdateMessage {
2224                message_id: MessageId(clock::Lamport::default()),
2225                metadata: MessageMetadata {
2226                    role: metadata.role,
2227                    status: metadata.status,
2228                    timestamp,
2229                },
2230                version: version.clone(),
2231            });
2232            version.observe(timestamp);
2233        }
2234
2235        let timestamp = next_timestamp.tick();
2236        operations.push(ContextOperation::SlashCommandFinished {
2237            id: SlashCommandId(timestamp),
2238            output_range: language::Anchor::MIN..language::Anchor::MAX,
2239            sections: self
2240                .slash_command_output_sections
2241                .into_iter()
2242                .map(|section| {
2243                    let buffer = buffer.read(cx);
2244                    SlashCommandOutputSection {
2245                        range: buffer.anchor_after(section.range.start)
2246                            ..buffer.anchor_before(section.range.end),
2247                        icon: section.icon,
2248                        label: section.label,
2249                    }
2250                })
2251                .collect(),
2252            version: version.clone(),
2253        });
2254        version.observe(timestamp);
2255
2256        let timestamp = next_timestamp.tick();
2257        operations.push(ContextOperation::UpdateSummary {
2258            summary: ContextSummary {
2259                text: self.summary,
2260                done: true,
2261                timestamp,
2262            },
2263            version: version.clone(),
2264        });
2265        version.observe(timestamp);
2266
2267        operations
2268    }
2269}
2270
2271#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
2272struct SavedMessageIdPreV0_4_0(usize);
2273
2274#[derive(Serialize, Deserialize)]
2275struct SavedMessagePreV0_4_0 {
2276    id: SavedMessageIdPreV0_4_0,
2277    start: usize,
2278}
2279
2280#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2281struct SavedMessageMetadataPreV0_4_0 {
2282    role: Role,
2283    status: MessageStatus,
2284}
2285
2286#[derive(Serialize, Deserialize)]
2287struct SavedContextV0_3_0 {
2288    id: Option<ContextId>,
2289    zed: String,
2290    version: String,
2291    text: String,
2292    messages: Vec<SavedMessagePreV0_4_0>,
2293    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2294    summary: String,
2295    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2296}
2297
2298impl SavedContextV0_3_0 {
2299    const VERSION: &'static str = "0.3.0";
2300
2301    fn upgrade(self) -> SavedContext {
2302        SavedContext {
2303            id: self.id,
2304            zed: self.zed,
2305            version: SavedContext::VERSION.into(),
2306            text: self.text,
2307            messages: self
2308                .messages
2309                .into_iter()
2310                .filter_map(|message| {
2311                    let metadata = self.message_metadata.get(&message.id)?;
2312                    let timestamp = clock::Lamport {
2313                        replica_id: ReplicaId::default(),
2314                        value: message.id.0 as u32,
2315                    };
2316                    Some(SavedMessage {
2317                        id: MessageId(timestamp),
2318                        start: message.start,
2319                        metadata: MessageMetadata {
2320                            role: metadata.role,
2321                            status: metadata.status.clone(),
2322                            timestamp,
2323                        },
2324                        image_offsets: Vec::new(),
2325                    })
2326                })
2327                .collect(),
2328            summary: self.summary,
2329            slash_command_output_sections: self.slash_command_output_sections,
2330        }
2331    }
2332}
2333
2334#[derive(Serialize, Deserialize)]
2335struct SavedContextV0_2_0 {
2336    id: Option<ContextId>,
2337    zed: String,
2338    version: String,
2339    text: String,
2340    messages: Vec<SavedMessagePreV0_4_0>,
2341    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2342    summary: String,
2343}
2344
2345impl SavedContextV0_2_0 {
2346    const VERSION: &'static str = "0.2.0";
2347
2348    fn upgrade(self) -> SavedContext {
2349        SavedContextV0_3_0 {
2350            id: self.id,
2351            zed: self.zed,
2352            version: SavedContextV0_3_0::VERSION.to_string(),
2353            text: self.text,
2354            messages: self.messages,
2355            message_metadata: self.message_metadata,
2356            summary: self.summary,
2357            slash_command_output_sections: Vec::new(),
2358        }
2359        .upgrade()
2360    }
2361}
2362
2363#[derive(Serialize, Deserialize)]
2364struct SavedContextV0_1_0 {
2365    id: Option<ContextId>,
2366    zed: String,
2367    version: String,
2368    text: String,
2369    messages: Vec<SavedMessagePreV0_4_0>,
2370    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2371    summary: String,
2372    api_url: Option<String>,
2373    model: OpenAiModel,
2374}
2375
2376impl SavedContextV0_1_0 {
2377    const VERSION: &'static str = "0.1.0";
2378
2379    fn upgrade(self) -> SavedContext {
2380        SavedContextV0_2_0 {
2381            id: self.id,
2382            zed: self.zed,
2383            version: SavedContextV0_2_0::VERSION.to_string(),
2384            text: self.text,
2385            messages: self.messages,
2386            message_metadata: self.message_metadata,
2387            summary: self.summary,
2388        }
2389        .upgrade()
2390    }
2391}
2392
2393#[derive(Clone)]
2394pub struct SavedContextMetadata {
2395    pub title: String,
2396    pub path: PathBuf,
2397    pub mtime: chrono::DateTime<chrono::Local>,
2398}