context.rs

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