context.rs

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