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        // Don't attach tools for now; we'll be removing tool use from
2308        // Assistant1 shortly.
2309        #[allow(clippy::overly_complex_bool_expr)]
2310        if false && cx.has_flag::<ToolUseFeatureFlag>() {
2311            request.tools = self
2312                .tools
2313                .tools(cx)
2314                .into_iter()
2315                .map(|tool| LanguageModelRequestTool {
2316                    name: tool.name(),
2317                    description: tool.description(),
2318                    input_schema: tool.input_schema(),
2319                })
2320                .collect();
2321        }
2322
2323        let assistant_message = self
2324            .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
2325            .unwrap();
2326
2327        // Queue up the user's next reply.
2328        let user_message = self
2329            .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
2330            .unwrap();
2331
2332        let pending_completion_id = post_inc(&mut self.completion_count);
2333
2334        let task = cx.spawn({
2335            |this, mut cx| async move {
2336                let stream = model.stream_completion(request, &cx);
2337                let assistant_message_id = assistant_message.id;
2338                let mut response_latency = None;
2339                let stream_completion = async {
2340                    let request_start = Instant::now();
2341                    let mut events = stream.await?;
2342                    let mut stop_reason = StopReason::EndTurn;
2343
2344                    while let Some(event) = events.next().await {
2345                        if response_latency.is_none() {
2346                            response_latency = Some(request_start.elapsed());
2347                        }
2348                        let event = event?;
2349
2350                        this.update(&mut cx, |this, cx| {
2351                            let message_ix = this
2352                                .message_anchors
2353                                .iter()
2354                                .position(|message| message.id == assistant_message_id)?;
2355                            this.buffer.update(cx, |buffer, cx| {
2356                                let message_old_end_offset = this.message_anchors[message_ix + 1..]
2357                                    .iter()
2358                                    .find(|message| message.start.is_valid(buffer))
2359                                    .map_or(buffer.len(), |message| {
2360                                        message.start.to_offset(buffer).saturating_sub(1)
2361                                    });
2362
2363                                match event {
2364                                    LanguageModelCompletionEvent::StartMessage { .. } => {}
2365                                    LanguageModelCompletionEvent::Stop(reason) => {
2366                                        stop_reason = reason;
2367                                    }
2368                                    LanguageModelCompletionEvent::Text(chunk) => {
2369                                        buffer.edit(
2370                                            [(
2371                                                message_old_end_offset..message_old_end_offset,
2372                                                chunk,
2373                                            )],
2374                                            None,
2375                                            cx,
2376                                        );
2377                                    }
2378                                    LanguageModelCompletionEvent::ToolUse(tool_use) => {
2379                                        const NEWLINE: char = '\n';
2380
2381                                        let mut text = String::new();
2382                                        text.push(NEWLINE);
2383                                        text.push_str(
2384                                            &serde_json::to_string_pretty(&tool_use)
2385                                                .expect("failed to serialize tool use to JSON"),
2386                                        );
2387                                        text.push(NEWLINE);
2388                                        let text_len = text.len();
2389
2390                                        buffer.edit(
2391                                            [(
2392                                                message_old_end_offset..message_old_end_offset,
2393                                                text,
2394                                            )],
2395                                            None,
2396                                            cx,
2397                                        );
2398
2399                                        let start_ix = message_old_end_offset + NEWLINE.len_utf8();
2400                                        let end_ix =
2401                                            message_old_end_offset + text_len - NEWLINE.len_utf8();
2402                                        let source_range = buffer.anchor_after(start_ix)
2403                                            ..buffer.anchor_after(end_ix);
2404
2405                                        this.pending_tool_uses_by_id.insert(
2406                                            tool_use.id.clone(),
2407                                            PendingToolUse {
2408                                                id: tool_use.id,
2409                                                name: tool_use.name,
2410                                                input: tool_use.input,
2411                                                status: PendingToolUseStatus::Idle,
2412                                                source_range,
2413                                            },
2414                                        );
2415                                    }
2416                                }
2417                            });
2418
2419                            cx.emit(ContextEvent::StreamedCompletion);
2420
2421                            Some(())
2422                        })?;
2423                        smol::future::yield_now().await;
2424                    }
2425                    this.update(&mut cx, |this, cx| {
2426                        this.pending_completions
2427                            .retain(|completion| completion.id != pending_completion_id);
2428                        this.summarize(false, cx);
2429                        this.update_cache_status_for_completion(cx);
2430                    })?;
2431
2432                    anyhow::Ok(stop_reason)
2433                };
2434
2435                let result = stream_completion.await;
2436
2437                this.update(&mut cx, |this, cx| {
2438                    let error_message = if let Some(error) = result.as_ref().err() {
2439                        if error.is::<PaymentRequiredError>() {
2440                            cx.emit(ContextEvent::ShowPaymentRequiredError);
2441                            this.update_metadata(assistant_message_id, cx, |metadata| {
2442                                metadata.status = MessageStatus::Canceled;
2443                            });
2444                            Some(error.to_string())
2445                        } else if error.is::<MaxMonthlySpendReachedError>() {
2446                            cx.emit(ContextEvent::ShowMaxMonthlySpendReachedError);
2447                            this.update_metadata(assistant_message_id, cx, |metadata| {
2448                                metadata.status = MessageStatus::Canceled;
2449                            });
2450                            Some(error.to_string())
2451                        } else {
2452                            let error_message = error
2453                                .chain()
2454                                .map(|err| err.to_string())
2455                                .collect::<Vec<_>>()
2456                                .join("\n");
2457                            cx.emit(ContextEvent::ShowAssistError(SharedString::from(
2458                                error_message.clone(),
2459                            )));
2460                            this.update_metadata(assistant_message_id, cx, |metadata| {
2461                                metadata.status =
2462                                    MessageStatus::Error(SharedString::from(error_message.clone()));
2463                            });
2464                            Some(error_message)
2465                        }
2466                    } else {
2467                        this.update_metadata(assistant_message_id, cx, |metadata| {
2468                            metadata.status = MessageStatus::Done;
2469                        });
2470                        None
2471                    };
2472
2473                    let language_name = this
2474                        .buffer
2475                        .read(cx)
2476                        .language()
2477                        .map(|language| language.name());
2478                    report_assistant_event(
2479                        AssistantEvent {
2480                            conversation_id: Some(this.id.0.clone()),
2481                            kind: AssistantKind::Panel,
2482                            phase: AssistantPhase::Response,
2483                            message_id: None,
2484                            model: model.telemetry_id(),
2485                            model_provider: model.provider_id().to_string(),
2486                            response_latency,
2487                            error_message,
2488                            language_name: language_name.map(|name| name.to_proto()),
2489                        },
2490                        this.telemetry.clone(),
2491                        cx.http_client(),
2492                        model.api_key(cx),
2493                        cx.background_executor(),
2494                    );
2495
2496                    if let Ok(stop_reason) = result {
2497                        match stop_reason {
2498                            StopReason::ToolUse => {
2499                                cx.emit(ContextEvent::UsePendingTools);
2500                            }
2501                            StopReason::EndTurn => {}
2502                            StopReason::MaxTokens => {}
2503                        }
2504                    }
2505                })
2506                .ok();
2507            }
2508        });
2509
2510        self.pending_completions.push(PendingCompletion {
2511            id: pending_completion_id,
2512            assistant_message_id: assistant_message.id,
2513            _task: task,
2514        });
2515
2516        Some(user_message)
2517    }
2518
2519    pub fn to_completion_request(
2520        &self,
2521        request_type: RequestType,
2522        cx: &AppContext,
2523    ) -> LanguageModelRequest {
2524        let buffer = self.buffer.read(cx);
2525
2526        let mut contents = self.contents(cx).peekable();
2527
2528        fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2529            let text: String = buffer.text_for_range(range.clone()).collect();
2530            if text.trim().is_empty() {
2531                None
2532            } else {
2533                Some(text)
2534            }
2535        }
2536
2537        let mut completion_request = LanguageModelRequest {
2538            messages: Vec::new(),
2539            tools: Vec::new(),
2540            stop: Vec::new(),
2541            temperature: None,
2542        };
2543        for message in self.messages(cx) {
2544            if message.status != MessageStatus::Done {
2545                continue;
2546            }
2547
2548            let mut offset = message.offset_range.start;
2549            let mut request_message = LanguageModelRequestMessage {
2550                role: message.role,
2551                content: Vec::new(),
2552                cache: message
2553                    .cache
2554                    .as_ref()
2555                    .map_or(false, |cache| cache.is_anchor),
2556            };
2557
2558            while let Some(content) = contents.peek() {
2559                if content
2560                    .range()
2561                    .end
2562                    .cmp(&message.anchor_range.end, buffer)
2563                    .is_lt()
2564                {
2565                    let content = contents.next().unwrap();
2566                    let range = content.range().to_offset(buffer);
2567                    request_message.content.extend(
2568                        collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2569                    );
2570
2571                    match content {
2572                        Content::Image { image, .. } => {
2573                            if let Some(image) = image.clone().now_or_never().flatten() {
2574                                request_message
2575                                    .content
2576                                    .push(language_model::MessageContent::Image(image));
2577                            }
2578                        }
2579                        Content::ToolUse { tool_use, .. } => {
2580                            request_message
2581                                .content
2582                                .push(language_model::MessageContent::ToolUse(tool_use.clone()));
2583                        }
2584                        Content::ToolResult { tool_use_id, .. } => {
2585                            request_message.content.push(
2586                                language_model::MessageContent::ToolResult(
2587                                    LanguageModelToolResult {
2588                                        tool_use_id: tool_use_id.to_string(),
2589                                        is_error: false,
2590                                        content: collect_text_content(buffer, range.clone())
2591                                            .unwrap_or_default(),
2592                                    },
2593                                ),
2594                            );
2595                        }
2596                    }
2597
2598                    offset = range.end;
2599                } else {
2600                    break;
2601                }
2602            }
2603
2604            request_message.content.extend(
2605                collect_text_content(buffer, offset..message.offset_range.end)
2606                    .map(MessageContent::Text),
2607            );
2608
2609            completion_request.messages.push(request_message);
2610        }
2611
2612        if let RequestType::SuggestEdits = request_type {
2613            if let Ok(preamble) = self.prompt_builder.generate_suggest_edits_prompt() {
2614                let last_elem_index = completion_request.messages.len();
2615
2616                completion_request
2617                    .messages
2618                    .push(LanguageModelRequestMessage {
2619                        role: Role::User,
2620                        content: vec![MessageContent::Text(preamble)],
2621                        cache: false,
2622                    });
2623
2624                // The preamble message should be sent right before the last actual user message.
2625                completion_request
2626                    .messages
2627                    .swap(last_elem_index, last_elem_index.saturating_sub(1));
2628            }
2629        }
2630
2631        completion_request
2632    }
2633
2634    pub fn cancel_last_assist(&mut self, cx: &mut ModelContext<Self>) -> bool {
2635        if let Some(pending_completion) = self.pending_completions.pop() {
2636            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2637                if metadata.status == MessageStatus::Pending {
2638                    metadata.status = MessageStatus::Canceled;
2639                }
2640            });
2641            true
2642        } else {
2643            false
2644        }
2645    }
2646
2647    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
2648        for id in &ids {
2649            if let Some(metadata) = self.messages_metadata.get(id) {
2650                let role = metadata.role.cycle();
2651                self.update_metadata(*id, cx, |metadata| metadata.role = role);
2652            }
2653        }
2654
2655        self.message_roles_updated(ids, cx);
2656    }
2657
2658    fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
2659        let mut ranges = Vec::new();
2660        for message in self.messages(cx) {
2661            if ids.contains(&message.id) {
2662                ranges.push(message.anchor_range.clone());
2663            }
2664        }
2665
2666        let buffer = self.buffer.read(cx).text_snapshot();
2667        let mut updated = Vec::new();
2668        let mut removed = Vec::new();
2669        for range in ranges {
2670            self.reparse_patches_in_range(range, &buffer, &mut updated, &mut removed, cx);
2671        }
2672
2673        if !updated.is_empty() || !removed.is_empty() {
2674            cx.emit(ContextEvent::PatchesUpdated { removed, updated })
2675        }
2676    }
2677
2678    pub fn update_metadata(
2679        &mut self,
2680        id: MessageId,
2681        cx: &mut ModelContext<Self>,
2682        f: impl FnOnce(&mut MessageMetadata),
2683    ) {
2684        let version = self.version.clone();
2685        let timestamp = self.next_timestamp();
2686        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2687            f(metadata);
2688            metadata.timestamp = timestamp;
2689            let operation = ContextOperation::UpdateMessage {
2690                message_id: id,
2691                metadata: metadata.clone(),
2692                version,
2693            };
2694            self.push_op(operation, cx);
2695            cx.emit(ContextEvent::MessagesEdited);
2696            cx.notify();
2697        }
2698    }
2699
2700    pub fn insert_message_after(
2701        &mut self,
2702        message_id: MessageId,
2703        role: Role,
2704        status: MessageStatus,
2705        cx: &mut ModelContext<Self>,
2706    ) -> Option<MessageAnchor> {
2707        if let Some(prev_message_ix) = self
2708            .message_anchors
2709            .iter()
2710            .position(|message| message.id == message_id)
2711        {
2712            // Find the next valid message after the one we were given.
2713            let mut next_message_ix = prev_message_ix + 1;
2714            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2715                if next_message.start.is_valid(self.buffer.read(cx)) {
2716                    break;
2717                }
2718                next_message_ix += 1;
2719            }
2720
2721            let buffer = self.buffer.read(cx);
2722            let offset = self
2723                .message_anchors
2724                .get(next_message_ix)
2725                .map_or(buffer.len(), |message| {
2726                    buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
2727                });
2728            Some(self.insert_message_at_offset(offset, role, status, cx))
2729        } else {
2730            None
2731        }
2732    }
2733
2734    fn insert_message_at_offset(
2735        &mut self,
2736        offset: usize,
2737        role: Role,
2738        status: MessageStatus,
2739        cx: &mut ModelContext<Self>,
2740    ) -> MessageAnchor {
2741        let start = self.buffer.update(cx, |buffer, cx| {
2742            buffer.edit([(offset..offset, "\n")], None, cx);
2743            buffer.anchor_before(offset + 1)
2744        });
2745
2746        let version = self.version.clone();
2747        let anchor = MessageAnchor {
2748            id: MessageId(self.next_timestamp()),
2749            start,
2750        };
2751        let metadata = MessageMetadata {
2752            role,
2753            status,
2754            timestamp: anchor.id.0,
2755            cache: None,
2756        };
2757        self.insert_message(anchor.clone(), metadata.clone(), cx);
2758        self.push_op(
2759            ContextOperation::InsertMessage {
2760                anchor: anchor.clone(),
2761                metadata,
2762                version,
2763            },
2764            cx,
2765        );
2766        anchor
2767    }
2768
2769    pub fn insert_content(&mut self, content: Content, cx: &mut ModelContext<Self>) {
2770        let buffer = self.buffer.read(cx);
2771        let insertion_ix = match self
2772            .contents
2773            .binary_search_by(|probe| probe.cmp(&content, buffer))
2774        {
2775            Ok(ix) => {
2776                self.contents.remove(ix);
2777                ix
2778            }
2779            Err(ix) => ix,
2780        };
2781        self.contents.insert(insertion_ix, content);
2782        cx.emit(ContextEvent::MessagesEdited);
2783    }
2784
2785    pub fn contents<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Content> {
2786        let buffer = self.buffer.read(cx);
2787        self.contents
2788            .iter()
2789            .filter(|content| {
2790                let range = content.range();
2791                range.start.is_valid(buffer) && range.end.is_valid(buffer)
2792            })
2793            .cloned()
2794    }
2795
2796    pub fn split_message(
2797        &mut self,
2798        range: Range<usize>,
2799        cx: &mut ModelContext<Self>,
2800    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2801        let start_message = self.message_for_offset(range.start, cx);
2802        let end_message = self.message_for_offset(range.end, cx);
2803        if let Some((start_message, end_message)) = start_message.zip(end_message) {
2804            // Prevent splitting when range spans multiple messages.
2805            if start_message.id != end_message.id {
2806                return (None, None);
2807            }
2808
2809            let message = start_message;
2810            let role = message.role;
2811            let mut edited_buffer = false;
2812
2813            let mut suffix_start = None;
2814
2815            // TODO: why did this start panicking?
2816            if range.start > message.offset_range.start
2817                && range.end < message.offset_range.end.saturating_sub(1)
2818            {
2819                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2820                    suffix_start = Some(range.end + 1);
2821                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2822                    suffix_start = Some(range.end);
2823                }
2824            }
2825
2826            let version = self.version.clone();
2827            let suffix = if let Some(suffix_start) = suffix_start {
2828                MessageAnchor {
2829                    id: MessageId(self.next_timestamp()),
2830                    start: self.buffer.read(cx).anchor_before(suffix_start),
2831                }
2832            } else {
2833                self.buffer.update(cx, |buffer, cx| {
2834                    buffer.edit([(range.end..range.end, "\n")], None, cx);
2835                });
2836                edited_buffer = true;
2837                MessageAnchor {
2838                    id: MessageId(self.next_timestamp()),
2839                    start: self.buffer.read(cx).anchor_before(range.end + 1),
2840                }
2841            };
2842
2843            let suffix_metadata = MessageMetadata {
2844                role,
2845                status: MessageStatus::Done,
2846                timestamp: suffix.id.0,
2847                cache: None,
2848            };
2849            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2850            self.push_op(
2851                ContextOperation::InsertMessage {
2852                    anchor: suffix.clone(),
2853                    metadata: suffix_metadata,
2854                    version,
2855                },
2856                cx,
2857            );
2858
2859            let new_messages =
2860                if range.start == range.end || range.start == message.offset_range.start {
2861                    (None, Some(suffix))
2862                } else {
2863                    let mut prefix_end = None;
2864                    if range.start > message.offset_range.start
2865                        && range.end < message.offset_range.end - 1
2866                    {
2867                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2868                            prefix_end = Some(range.start + 1);
2869                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2870                            == Some('\n')
2871                        {
2872                            prefix_end = Some(range.start);
2873                        }
2874                    }
2875
2876                    let version = self.version.clone();
2877                    let selection = if let Some(prefix_end) = prefix_end {
2878                        MessageAnchor {
2879                            id: MessageId(self.next_timestamp()),
2880                            start: self.buffer.read(cx).anchor_before(prefix_end),
2881                        }
2882                    } else {
2883                        self.buffer.update(cx, |buffer, cx| {
2884                            buffer.edit([(range.start..range.start, "\n")], None, cx)
2885                        });
2886                        edited_buffer = true;
2887                        MessageAnchor {
2888                            id: MessageId(self.next_timestamp()),
2889                            start: self.buffer.read(cx).anchor_before(range.end + 1),
2890                        }
2891                    };
2892
2893                    let selection_metadata = MessageMetadata {
2894                        role,
2895                        status: MessageStatus::Done,
2896                        timestamp: selection.id.0,
2897                        cache: None,
2898                    };
2899                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2900                    self.push_op(
2901                        ContextOperation::InsertMessage {
2902                            anchor: selection.clone(),
2903                            metadata: selection_metadata,
2904                            version,
2905                        },
2906                        cx,
2907                    );
2908
2909                    (Some(selection), Some(suffix))
2910                };
2911
2912            if !edited_buffer {
2913                cx.emit(ContextEvent::MessagesEdited);
2914            }
2915            new_messages
2916        } else {
2917            (None, None)
2918        }
2919    }
2920
2921    fn insert_message(
2922        &mut self,
2923        new_anchor: MessageAnchor,
2924        new_metadata: MessageMetadata,
2925        cx: &mut ModelContext<Self>,
2926    ) {
2927        cx.emit(ContextEvent::MessagesEdited);
2928
2929        self.messages_metadata.insert(new_anchor.id, new_metadata);
2930
2931        let buffer = self.buffer.read(cx);
2932        let insertion_ix = self
2933            .message_anchors
2934            .iter()
2935            .position(|anchor| {
2936                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2937                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2938            })
2939            .unwrap_or(self.message_anchors.len());
2940        self.message_anchors.insert(insertion_ix, new_anchor);
2941    }
2942
2943    pub fn summarize(&mut self, replace_old: bool, cx: &mut ModelContext<Self>) {
2944        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
2945            return;
2946        };
2947        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
2948            return;
2949        };
2950
2951        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
2952            if !provider.is_authenticated(cx) {
2953                return;
2954            }
2955
2956            let mut request = self.to_completion_request(RequestType::Chat, cx);
2957            request.messages.push(LanguageModelRequestMessage {
2958                role: Role::User,
2959                content: vec![
2960                    "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:`"
2961                        .into(),
2962                ],
2963                cache: false,
2964            });
2965
2966            self.pending_summary = cx.spawn(|this, mut cx| {
2967                async move {
2968                    let stream = model.stream_completion_text(request, &cx);
2969                    let mut messages = stream.await?;
2970
2971                    let mut replaced = !replace_old;
2972                    while let Some(message) = messages.stream.next().await {
2973                        let text = message?;
2974                        let mut lines = text.lines();
2975                        this.update(&mut cx, |this, cx| {
2976                            let version = this.version.clone();
2977                            let timestamp = this.next_timestamp();
2978                            let summary = this.summary.get_or_insert(ContextSummary::default());
2979                            if !replaced && replace_old {
2980                                summary.text.clear();
2981                                replaced = true;
2982                            }
2983                            summary.text.extend(lines.next());
2984                            summary.timestamp = timestamp;
2985                            let operation = ContextOperation::UpdateSummary {
2986                                summary: summary.clone(),
2987                                version,
2988                            };
2989                            this.push_op(operation, cx);
2990                            cx.emit(ContextEvent::SummaryChanged);
2991                        })?;
2992
2993                        // Stop if the LLM generated multiple lines.
2994                        if lines.next().is_some() {
2995                            break;
2996                        }
2997                    }
2998
2999                    this.update(&mut cx, |this, cx| {
3000                        let version = this.version.clone();
3001                        let timestamp = this.next_timestamp();
3002                        if let Some(summary) = this.summary.as_mut() {
3003                            summary.done = true;
3004                            summary.timestamp = timestamp;
3005                            let operation = ContextOperation::UpdateSummary {
3006                                summary: summary.clone(),
3007                                version,
3008                            };
3009                            this.push_op(operation, cx);
3010                            cx.emit(ContextEvent::SummaryChanged);
3011                        }
3012                    })?;
3013
3014                    anyhow::Ok(())
3015                }
3016                .log_err()
3017            });
3018        }
3019    }
3020
3021    fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
3022        self.messages_for_offsets([offset], cx).pop()
3023    }
3024
3025    pub fn messages_for_offsets(
3026        &self,
3027        offsets: impl IntoIterator<Item = usize>,
3028        cx: &AppContext,
3029    ) -> Vec<Message> {
3030        let mut result = Vec::new();
3031
3032        let mut messages = self.messages(cx).peekable();
3033        let mut offsets = offsets.into_iter().peekable();
3034        let mut current_message = messages.next();
3035        while let Some(offset) = offsets.next() {
3036            // Locate the message that contains the offset.
3037            while current_message.as_ref().map_or(false, |message| {
3038                !message.offset_range.contains(&offset) && messages.peek().is_some()
3039            }) {
3040                current_message = messages.next();
3041            }
3042            let Some(message) = current_message.as_ref() else {
3043                break;
3044            };
3045
3046            // Skip offsets that are in the same message.
3047            while offsets.peek().map_or(false, |offset| {
3048                message.offset_range.contains(offset) || messages.peek().is_none()
3049            }) {
3050                offsets.next();
3051            }
3052
3053            result.push(message.clone());
3054        }
3055        result
3056    }
3057
3058    fn messages_from_anchors<'a>(
3059        &'a self,
3060        message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
3061        cx: &'a AppContext,
3062    ) -> impl 'a + Iterator<Item = Message> {
3063        let buffer = self.buffer.read(cx);
3064
3065        Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
3066    }
3067
3068    pub fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
3069        self.messages_from_anchors(self.message_anchors.iter(), cx)
3070    }
3071
3072    pub fn messages_from_iters<'a>(
3073        buffer: &'a Buffer,
3074        metadata: &'a HashMap<MessageId, MessageMetadata>,
3075        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
3076    ) -> impl 'a + Iterator<Item = Message> {
3077        let mut messages = messages.peekable();
3078
3079        iter::from_fn(move || {
3080            if let Some((start_ix, message_anchor)) = messages.next() {
3081                let metadata = metadata.get(&message_anchor.id)?;
3082
3083                let message_start = message_anchor.start.to_offset(buffer);
3084                let mut message_end = None;
3085                let mut end_ix = start_ix;
3086                while let Some((_, next_message)) = messages.peek() {
3087                    if next_message.start.is_valid(buffer) {
3088                        message_end = Some(next_message.start);
3089                        break;
3090                    } else {
3091                        end_ix += 1;
3092                        messages.next();
3093                    }
3094                }
3095                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
3096                let message_end = message_end_anchor.to_offset(buffer);
3097
3098                return Some(Message {
3099                    index_range: start_ix..end_ix,
3100                    offset_range: message_start..message_end,
3101                    anchor_range: message_anchor.start..message_end_anchor,
3102                    id: message_anchor.id,
3103                    role: metadata.role,
3104                    status: metadata.status.clone(),
3105                    cache: metadata.cache.clone(),
3106                });
3107            }
3108            None
3109        })
3110    }
3111
3112    pub fn save(
3113        &mut self,
3114        debounce: Option<Duration>,
3115        fs: Arc<dyn Fs>,
3116        cx: &mut ModelContext<Context>,
3117    ) {
3118        if self.replica_id() != ReplicaId::default() {
3119            // Prevent saving a remote context for now.
3120            return;
3121        }
3122
3123        self.pending_save = cx.spawn(|this, mut cx| async move {
3124            if let Some(debounce) = debounce {
3125                cx.background_executor().timer(debounce).await;
3126            }
3127
3128            let (old_path, summary) = this.read_with(&cx, |this, _| {
3129                let path = this.path.clone();
3130                let summary = if let Some(summary) = this.summary.as_ref() {
3131                    if summary.done {
3132                        Some(summary.text.clone())
3133                    } else {
3134                        None
3135                    }
3136                } else {
3137                    None
3138                };
3139                (path, summary)
3140            })?;
3141
3142            if let Some(summary) = summary {
3143                let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
3144                let mut discriminant = 1;
3145                let mut new_path;
3146                loop {
3147                    new_path = contexts_dir().join(&format!(
3148                        "{} - {}.zed.json",
3149                        summary.trim(),
3150                        discriminant
3151                    ));
3152                    if fs.is_file(&new_path).await {
3153                        discriminant += 1;
3154                    } else {
3155                        break;
3156                    }
3157                }
3158
3159                fs.create_dir(contexts_dir().as_ref()).await?;
3160                fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
3161                    .await?;
3162                if let Some(old_path) = old_path {
3163                    if new_path != old_path {
3164                        fs.remove_file(
3165                            &old_path,
3166                            RemoveOptions {
3167                                recursive: false,
3168                                ignore_if_not_exists: true,
3169                            },
3170                        )
3171                        .await?;
3172                    }
3173                }
3174
3175                this.update(&mut cx, |this, _| this.path = Some(new_path))?;
3176            }
3177
3178            Ok(())
3179        });
3180    }
3181
3182    pub fn custom_summary(&mut self, custom_summary: String, cx: &mut ModelContext<Self>) {
3183        let timestamp = self.next_timestamp();
3184        let summary = self.summary.get_or_insert(ContextSummary::default());
3185        summary.timestamp = timestamp;
3186        summary.done = true;
3187        summary.text = custom_summary;
3188        cx.emit(ContextEvent::SummaryChanged);
3189    }
3190}
3191
3192fn trimmed_text_in_range(buffer: &BufferSnapshot, range: Range<text::Anchor>) -> String {
3193    let mut is_start = true;
3194    let mut content = buffer
3195        .text_for_range(range)
3196        .map(|mut chunk| {
3197            if is_start {
3198                chunk = chunk.trim_start_matches('\n');
3199                if !chunk.is_empty() {
3200                    is_start = false;
3201                }
3202            }
3203            chunk
3204        })
3205        .collect::<String>();
3206    content.truncate(content.trim_end().len());
3207    content
3208}
3209
3210#[derive(Debug, Default)]
3211pub struct ContextVersion {
3212    context: clock::Global,
3213    buffer: clock::Global,
3214}
3215
3216impl ContextVersion {
3217    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
3218        Self {
3219            context: language::proto::deserialize_version(&proto.context_version),
3220            buffer: language::proto::deserialize_version(&proto.buffer_version),
3221        }
3222    }
3223
3224    pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
3225        proto::ContextVersion {
3226            context_id: context_id.to_proto(),
3227            context_version: language::proto::serialize_version(&self.context),
3228            buffer_version: language::proto::serialize_version(&self.buffer),
3229        }
3230    }
3231}
3232
3233#[derive(Debug, Clone)]
3234pub struct ParsedSlashCommand {
3235    pub name: String,
3236    pub arguments: SmallVec<[String; 3]>,
3237    pub status: PendingSlashCommandStatus,
3238    pub source_range: Range<language::Anchor>,
3239}
3240
3241#[derive(Debug)]
3242pub struct InvokedSlashCommand {
3243    pub name: SharedString,
3244    pub range: Range<language::Anchor>,
3245    pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
3246    pub status: InvokedSlashCommandStatus,
3247    pub transaction: Option<language::TransactionId>,
3248    timestamp: clock::Lamport,
3249}
3250
3251#[derive(Debug)]
3252pub enum InvokedSlashCommandStatus {
3253    Running(Task<()>),
3254    Error(SharedString),
3255    Finished,
3256}
3257
3258#[derive(Debug, Clone)]
3259pub enum PendingSlashCommandStatus {
3260    Idle,
3261    Running { _task: Shared<Task<()>> },
3262    Error(String),
3263}
3264
3265#[derive(Debug, Clone)]
3266pub struct PendingToolUse {
3267    pub id: LanguageModelToolUseId,
3268    pub name: String,
3269    pub input: serde_json::Value,
3270    pub status: PendingToolUseStatus,
3271    pub source_range: Range<language::Anchor>,
3272}
3273
3274#[derive(Debug, Clone)]
3275pub enum PendingToolUseStatus {
3276    Idle,
3277    Running { _task: Shared<Task<()>> },
3278    Error(String),
3279}
3280
3281impl PendingToolUseStatus {
3282    pub fn is_idle(&self) -> bool {
3283        matches!(self, PendingToolUseStatus::Idle)
3284    }
3285}
3286
3287#[derive(Serialize, Deserialize)]
3288pub struct SavedMessage {
3289    pub id: MessageId,
3290    pub start: usize,
3291    pub metadata: MessageMetadata,
3292}
3293
3294#[derive(Serialize, Deserialize)]
3295pub struct SavedContext {
3296    pub id: Option<ContextId>,
3297    pub zed: String,
3298    pub version: String,
3299    pub text: String,
3300    pub messages: Vec<SavedMessage>,
3301    pub summary: String,
3302    pub slash_command_output_sections:
3303        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3304}
3305
3306impl SavedContext {
3307    pub const VERSION: &'static str = "0.4.0";
3308
3309    pub fn from_json(json: &str) -> Result<Self> {
3310        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3311        match saved_context_json
3312            .get("version")
3313            .ok_or_else(|| anyhow!("version not found"))?
3314        {
3315            serde_json::Value::String(version) => match version.as_str() {
3316                SavedContext::VERSION => {
3317                    Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
3318                }
3319                SavedContextV0_3_0::VERSION => {
3320                    let saved_context =
3321                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3322                    Ok(saved_context.upgrade())
3323                }
3324                SavedContextV0_2_0::VERSION => {
3325                    let saved_context =
3326                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3327                    Ok(saved_context.upgrade())
3328                }
3329                SavedContextV0_1_0::VERSION => {
3330                    let saved_context =
3331                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3332                    Ok(saved_context.upgrade())
3333                }
3334                _ => Err(anyhow!("unrecognized saved context version: {}", version)),
3335            },
3336            _ => Err(anyhow!("version not found on saved context")),
3337        }
3338    }
3339
3340    fn into_ops(
3341        self,
3342        buffer: &Model<Buffer>,
3343        cx: &mut ModelContext<Context>,
3344    ) -> Vec<ContextOperation> {
3345        let mut operations = Vec::new();
3346        let mut version = clock::Global::new();
3347        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3348
3349        let mut first_message_metadata = None;
3350        for message in self.messages {
3351            if message.id == MessageId(clock::Lamport::default()) {
3352                first_message_metadata = Some(message.metadata);
3353            } else {
3354                operations.push(ContextOperation::InsertMessage {
3355                    anchor: MessageAnchor {
3356                        id: message.id,
3357                        start: buffer.read(cx).anchor_before(message.start),
3358                    },
3359                    metadata: MessageMetadata {
3360                        role: message.metadata.role,
3361                        status: message.metadata.status,
3362                        timestamp: message.metadata.timestamp,
3363                        cache: None,
3364                    },
3365                    version: version.clone(),
3366                });
3367                version.observe(message.id.0);
3368                next_timestamp.observe(message.id.0);
3369            }
3370        }
3371
3372        if let Some(metadata) = first_message_metadata {
3373            let timestamp = next_timestamp.tick();
3374            operations.push(ContextOperation::UpdateMessage {
3375                message_id: MessageId(clock::Lamport::default()),
3376                metadata: MessageMetadata {
3377                    role: metadata.role,
3378                    status: metadata.status,
3379                    timestamp,
3380                    cache: None,
3381                },
3382                version: version.clone(),
3383            });
3384            version.observe(timestamp);
3385        }
3386
3387        let buffer = buffer.read(cx);
3388        for section in self.slash_command_output_sections {
3389            let timestamp = next_timestamp.tick();
3390            operations.push(ContextOperation::SlashCommandOutputSectionAdded {
3391                timestamp,
3392                section: SlashCommandOutputSection {
3393                    range: buffer.anchor_after(section.range.start)
3394                        ..buffer.anchor_before(section.range.end),
3395                    icon: section.icon,
3396                    label: section.label,
3397                    metadata: section.metadata,
3398                },
3399                version: version.clone(),
3400            });
3401
3402            version.observe(timestamp);
3403        }
3404
3405        let timestamp = next_timestamp.tick();
3406        operations.push(ContextOperation::UpdateSummary {
3407            summary: ContextSummary {
3408                text: self.summary,
3409                done: true,
3410                timestamp,
3411            },
3412            version: version.clone(),
3413        });
3414        version.observe(timestamp);
3415
3416        operations
3417    }
3418}
3419
3420#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3421struct SavedMessageIdPreV0_4_0(usize);
3422
3423#[derive(Serialize, Deserialize)]
3424struct SavedMessagePreV0_4_0 {
3425    id: SavedMessageIdPreV0_4_0,
3426    start: usize,
3427}
3428
3429#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3430struct SavedMessageMetadataPreV0_4_0 {
3431    role: Role,
3432    status: MessageStatus,
3433}
3434
3435#[derive(Serialize, Deserialize)]
3436struct SavedContextV0_3_0 {
3437    id: Option<ContextId>,
3438    zed: String,
3439    version: String,
3440    text: String,
3441    messages: Vec<SavedMessagePreV0_4_0>,
3442    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3443    summary: String,
3444    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3445}
3446
3447impl SavedContextV0_3_0 {
3448    const VERSION: &'static str = "0.3.0";
3449
3450    fn upgrade(self) -> SavedContext {
3451        SavedContext {
3452            id: self.id,
3453            zed: self.zed,
3454            version: SavedContext::VERSION.into(),
3455            text: self.text,
3456            messages: self
3457                .messages
3458                .into_iter()
3459                .filter_map(|message| {
3460                    let metadata = self.message_metadata.get(&message.id)?;
3461                    let timestamp = clock::Lamport {
3462                        replica_id: ReplicaId::default(),
3463                        value: message.id.0 as u32,
3464                    };
3465                    Some(SavedMessage {
3466                        id: MessageId(timestamp),
3467                        start: message.start,
3468                        metadata: MessageMetadata {
3469                            role: metadata.role,
3470                            status: metadata.status.clone(),
3471                            timestamp,
3472                            cache: None,
3473                        },
3474                    })
3475                })
3476                .collect(),
3477            summary: self.summary,
3478            slash_command_output_sections: self.slash_command_output_sections,
3479        }
3480    }
3481}
3482
3483#[derive(Serialize, Deserialize)]
3484struct SavedContextV0_2_0 {
3485    id: Option<ContextId>,
3486    zed: String,
3487    version: String,
3488    text: String,
3489    messages: Vec<SavedMessagePreV0_4_0>,
3490    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3491    summary: String,
3492}
3493
3494impl SavedContextV0_2_0 {
3495    const VERSION: &'static str = "0.2.0";
3496
3497    fn upgrade(self) -> SavedContext {
3498        SavedContextV0_3_0 {
3499            id: self.id,
3500            zed: self.zed,
3501            version: SavedContextV0_3_0::VERSION.to_string(),
3502            text: self.text,
3503            messages: self.messages,
3504            message_metadata: self.message_metadata,
3505            summary: self.summary,
3506            slash_command_output_sections: Vec::new(),
3507        }
3508        .upgrade()
3509    }
3510}
3511
3512#[derive(Serialize, Deserialize)]
3513struct SavedContextV0_1_0 {
3514    id: Option<ContextId>,
3515    zed: String,
3516    version: String,
3517    text: String,
3518    messages: Vec<SavedMessagePreV0_4_0>,
3519    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3520    summary: String,
3521    api_url: Option<String>,
3522    model: OpenAiModel,
3523}
3524
3525impl SavedContextV0_1_0 {
3526    const VERSION: &'static str = "0.1.0";
3527
3528    fn upgrade(self) -> SavedContext {
3529        SavedContextV0_2_0 {
3530            id: self.id,
3531            zed: self.zed,
3532            version: SavedContextV0_2_0::VERSION.to_string(),
3533            text: self.text,
3534            messages: self.messages,
3535            message_metadata: self.message_metadata,
3536            summary: self.summary,
3537        }
3538        .upgrade()
3539    }
3540}
3541
3542#[derive(Clone)]
3543pub struct SavedContextMetadata {
3544    pub title: String,
3545    pub path: PathBuf,
3546    pub mtime: chrono::DateTime<chrono::Local>,
3547}