context.rs

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