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,
  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<Result<SlashCommandOutput>>,
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                this.update(&mut cx, |this, cx| match output {
1692                    Ok(mut output) => {
1693                        // Ensure section ranges are valid.
1694                        for section in &mut output.sections {
1695                            section.range.start = section.range.start.min(output.text.len());
1696                            section.range.end = section.range.end.min(output.text.len());
1697                            while !output.text.is_char_boundary(section.range.start) {
1698                                section.range.start -= 1;
1699                            }
1700                            while !output.text.is_char_boundary(section.range.end) {
1701                                section.range.end += 1;
1702                            }
1703                        }
1704
1705                        // Ensure there is a newline after the last section.
1706                        if ensure_trailing_newline {
1707                            let has_newline_after_last_section =
1708                                output.sections.last().map_or(false, |last_section| {
1709                                    output.text[last_section.range.end..].ends_with('\n')
1710                                });
1711                            if !has_newline_after_last_section {
1712                                output.text.push('\n');
1713                            }
1714                        }
1715
1716                        let version = this.version.clone();
1717                        let command_id = SlashCommandId(this.next_timestamp());
1718                        let (operation, event) = this.buffer.update(cx, |buffer, cx| {
1719                            let start = command_range.start.to_offset(buffer);
1720                            let old_end = command_range.end.to_offset(buffer);
1721                            let new_end = start + output.text.len();
1722                            buffer.edit([(start..old_end, output.text)], None, cx);
1723
1724                            let mut sections = output
1725                                .sections
1726                                .into_iter()
1727                                .map(|section| SlashCommandOutputSection {
1728                                    range: buffer.anchor_after(start + section.range.start)
1729                                        ..buffer.anchor_before(start + section.range.end),
1730                                    icon: section.icon,
1731                                    label: section.label,
1732                                    metadata: section.metadata,
1733                                })
1734                                .collect::<Vec<_>>();
1735                            sections.sort_by(|a, b| a.range.cmp(&b.range, buffer));
1736
1737                            this.slash_command_output_sections
1738                                .extend(sections.iter().cloned());
1739                            this.slash_command_output_sections
1740                                .sort_by(|a, b| a.range.cmp(&b.range, buffer));
1741
1742                            let output_range =
1743                                buffer.anchor_after(start)..buffer.anchor_before(new_end);
1744                            this.finished_slash_commands.insert(command_id);
1745
1746                            (
1747                                ContextOperation::SlashCommandFinished {
1748                                    id: command_id,
1749                                    output_range: output_range.clone(),
1750                                    sections: sections.clone(),
1751                                    version,
1752                                },
1753                                ContextEvent::SlashCommandFinished {
1754                                    output_range,
1755                                    sections,
1756                                    run_commands_in_output: output.run_commands_in_text,
1757                                    expand_result,
1758                                },
1759                            )
1760                        });
1761
1762                        this.push_op(operation, cx);
1763                        cx.emit(event);
1764                    }
1765                    Err(error) => {
1766                        if let Some(pending_command) =
1767                            this.pending_command_for_position(command_range.start, cx)
1768                        {
1769                            pending_command.status =
1770                                PendingSlashCommandStatus::Error(error.to_string());
1771                            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1772                                removed: vec![pending_command.source_range.clone()],
1773                                updated: vec![pending_command.clone()],
1774                            });
1775                        }
1776                    }
1777                })
1778                .ok();
1779            }
1780        });
1781
1782        if let Some(pending_command) = self.pending_command_for_position(command_range.start, cx) {
1783            pending_command.status = PendingSlashCommandStatus::Running {
1784                _task: insert_output_task.shared(),
1785            };
1786            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1787                removed: vec![pending_command.source_range.clone()],
1788                updated: vec![pending_command.clone()],
1789            });
1790        }
1791    }
1792
1793    pub fn insert_tool_output(
1794        &mut self,
1795        tool_use_id: Arc<str>,
1796        output: Task<Result<String>>,
1797        cx: &mut ModelContext<Self>,
1798    ) {
1799        let insert_output_task = cx.spawn(|this, mut cx| {
1800            let tool_use_id = tool_use_id.clone();
1801            async move {
1802                let output = output.await;
1803                this.update(&mut cx, |this, cx| match output {
1804                    Ok(mut output) => {
1805                        const NEWLINE: char = '\n';
1806
1807                        if !output.ends_with(NEWLINE) {
1808                            output.push(NEWLINE);
1809                        }
1810
1811                        let anchor_range = this.buffer.update(cx, |buffer, cx| {
1812                            let insert_start = buffer.len().to_offset(buffer);
1813                            let insert_end = insert_start;
1814
1815                            let start = insert_start;
1816                            let end = start + output.len() - NEWLINE.len_utf8();
1817
1818                            buffer.edit([(insert_start..insert_end, output)], None, cx);
1819
1820                            let output_range = buffer.anchor_after(start)..buffer.anchor_after(end);
1821
1822                            output_range
1823                        });
1824
1825                        this.insert_content(
1826                            Content::ToolResult {
1827                                range: anchor_range.clone(),
1828                                tool_use_id: tool_use_id.clone(),
1829                            },
1830                            cx,
1831                        );
1832
1833                        cx.emit(ContextEvent::ToolFinished {
1834                            tool_use_id,
1835                            output_range: anchor_range,
1836                        });
1837                    }
1838                    Err(err) => {
1839                        if let Some(tool_use) = this.pending_tool_uses_by_id.get_mut(&tool_use_id) {
1840                            tool_use.status = PendingToolUseStatus::Error(err.to_string());
1841                        }
1842                    }
1843                })
1844                .ok();
1845            }
1846        });
1847
1848        if let Some(tool_use) = self.pending_tool_uses_by_id.get_mut(&tool_use_id) {
1849            tool_use.status = PendingToolUseStatus::Running {
1850                _task: insert_output_task.shared(),
1851            };
1852        }
1853    }
1854
1855    pub fn completion_provider_changed(&mut self, cx: &mut ModelContext<Self>) {
1856        self.count_remaining_tokens(cx);
1857    }
1858
1859    fn get_last_valid_message_id(&self, cx: &ModelContext<Self>) -> Option<MessageId> {
1860        self.message_anchors.iter().rev().find_map(|message| {
1861            message
1862                .start
1863                .is_valid(self.buffer.read(cx))
1864                .then_some(message.id)
1865        })
1866    }
1867
1868    pub fn assist(&mut self, cx: &mut ModelContext<Self>) -> Option<MessageAnchor> {
1869        let model_registry = LanguageModelRegistry::read_global(cx);
1870        let provider = model_registry.active_provider()?;
1871        let model = model_registry.active_model()?;
1872        let last_message_id = self.get_last_valid_message_id(cx)?;
1873
1874        if !provider.is_authenticated(cx) {
1875            log::info!("completion provider has no credentials");
1876            return None;
1877        }
1878        // Compute which messages to cache, including the last one.
1879        self.mark_cache_anchors(&model.cache_configuration(), false, cx);
1880
1881        let mut request = self.to_completion_request(cx);
1882
1883        if cx.has_flag::<ToolUseFeatureFlag>() {
1884            let tool_registry = ToolRegistry::global(cx);
1885            request.tools = tool_registry
1886                .tools()
1887                .into_iter()
1888                .map(|tool| LanguageModelRequestTool {
1889                    name: tool.name(),
1890                    description: tool.description(),
1891                    input_schema: tool.input_schema(),
1892                })
1893                .collect();
1894        }
1895
1896        let assistant_message = self
1897            .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1898            .unwrap();
1899
1900        // Queue up the user's next reply.
1901        let user_message = self
1902            .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
1903            .unwrap();
1904
1905        let pending_completion_id = post_inc(&mut self.completion_count);
1906
1907        let task = cx.spawn({
1908            |this, mut cx| async move {
1909                let stream = model.stream_completion(request, &cx);
1910                let assistant_message_id = assistant_message.id;
1911                let mut response_latency = None;
1912                let stream_completion = async {
1913                    let request_start = Instant::now();
1914                    let mut events = stream.await?;
1915                    let mut stop_reason = StopReason::EndTurn;
1916
1917                    while let Some(event) = events.next().await {
1918                        if response_latency.is_none() {
1919                            response_latency = Some(request_start.elapsed());
1920                        }
1921                        let event = event?;
1922
1923                        this.update(&mut cx, |this, cx| {
1924                            let message_ix = this
1925                                .message_anchors
1926                                .iter()
1927                                .position(|message| message.id == assistant_message_id)?;
1928                            this.buffer.update(cx, |buffer, cx| {
1929                                let message_old_end_offset = this.message_anchors[message_ix + 1..]
1930                                    .iter()
1931                                    .find(|message| message.start.is_valid(buffer))
1932                                    .map_or(buffer.len(), |message| {
1933                                        message.start.to_offset(buffer).saturating_sub(1)
1934                                    });
1935
1936                                match event {
1937                                    LanguageModelCompletionEvent::Stop(reason) => {
1938                                        stop_reason = reason;
1939                                    }
1940                                    LanguageModelCompletionEvent::Text(chunk) => {
1941                                        buffer.edit(
1942                                            [(
1943                                                message_old_end_offset..message_old_end_offset,
1944                                                chunk,
1945                                            )],
1946                                            None,
1947                                            cx,
1948                                        );
1949                                    }
1950                                    LanguageModelCompletionEvent::ToolUse(tool_use) => {
1951                                        const NEWLINE: char = '\n';
1952
1953                                        let mut text = String::new();
1954                                        text.push(NEWLINE);
1955                                        text.push_str(
1956                                            &serde_json::to_string_pretty(&tool_use)
1957                                                .expect("failed to serialize tool use to JSON"),
1958                                        );
1959                                        text.push(NEWLINE);
1960                                        let text_len = text.len();
1961
1962                                        buffer.edit(
1963                                            [(
1964                                                message_old_end_offset..message_old_end_offset,
1965                                                text,
1966                                            )],
1967                                            None,
1968                                            cx,
1969                                        );
1970
1971                                        let start_ix = message_old_end_offset + NEWLINE.len_utf8();
1972                                        let end_ix =
1973                                            message_old_end_offset + text_len - NEWLINE.len_utf8();
1974                                        let source_range = buffer.anchor_after(start_ix)
1975                                            ..buffer.anchor_after(end_ix);
1976
1977                                        let tool_use_id: Arc<str> = tool_use.id.into();
1978                                        this.pending_tool_uses_by_id.insert(
1979                                            tool_use_id.clone(),
1980                                            PendingToolUse {
1981                                                id: tool_use_id,
1982                                                name: tool_use.name,
1983                                                input: tool_use.input,
1984                                                status: PendingToolUseStatus::Idle,
1985                                                source_range,
1986                                            },
1987                                        );
1988                                    }
1989                                }
1990                            });
1991
1992                            cx.emit(ContextEvent::StreamedCompletion);
1993
1994                            Some(())
1995                        })?;
1996                        smol::future::yield_now().await;
1997                    }
1998                    this.update(&mut cx, |this, cx| {
1999                        this.pending_completions
2000                            .retain(|completion| completion.id != pending_completion_id);
2001                        this.summarize(false, cx);
2002                        this.update_cache_status_for_completion(cx);
2003                    })?;
2004
2005                    anyhow::Ok(stop_reason)
2006                };
2007
2008                let result = stream_completion.await;
2009
2010                this.update(&mut cx, |this, cx| {
2011                    let error_message = if let Some(error) = result.as_ref().err() {
2012                        if error.is::<PaymentRequiredError>() {
2013                            cx.emit(ContextEvent::ShowPaymentRequiredError);
2014                            this.update_metadata(assistant_message_id, cx, |metadata| {
2015                                metadata.status = MessageStatus::Canceled;
2016                            });
2017                            Some(error.to_string())
2018                        } else if error.is::<MaxMonthlySpendReachedError>() {
2019                            cx.emit(ContextEvent::ShowMaxMonthlySpendReachedError);
2020                            this.update_metadata(assistant_message_id, cx, |metadata| {
2021                                metadata.status = MessageStatus::Canceled;
2022                            });
2023                            Some(error.to_string())
2024                        } else {
2025                            let error_message = error.to_string().trim().to_string();
2026                            cx.emit(ContextEvent::ShowAssistError(SharedString::from(
2027                                error_message.clone(),
2028                            )));
2029                            this.update_metadata(assistant_message_id, cx, |metadata| {
2030                                metadata.status =
2031                                    MessageStatus::Error(SharedString::from(error_message.clone()));
2032                            });
2033                            Some(error_message)
2034                        }
2035                    } else {
2036                        this.update_metadata(assistant_message_id, cx, |metadata| {
2037                            metadata.status = MessageStatus::Done;
2038                        });
2039                        None
2040                    };
2041
2042                    if let Some(telemetry) = this.telemetry.as_ref() {
2043                        let language_name = this
2044                            .buffer
2045                            .read(cx)
2046                            .language()
2047                            .map(|language| language.name());
2048                        telemetry.report_assistant_event(AssistantEvent {
2049                            conversation_id: Some(this.id.0.clone()),
2050                            kind: AssistantKind::Panel,
2051                            phase: AssistantPhase::Response,
2052                            model: model.telemetry_id(),
2053                            model_provider: model.provider_id().to_string(),
2054                            response_latency,
2055                            error_message,
2056                            language_name: language_name.map(|name| name.to_proto()),
2057                        });
2058                    }
2059
2060                    if let Ok(stop_reason) = result {
2061                        match stop_reason {
2062                            StopReason::ToolUse => {
2063                                cx.emit(ContextEvent::UsePendingTools);
2064                            }
2065                            StopReason::EndTurn => {}
2066                            StopReason::MaxTokens => {}
2067                        }
2068                    }
2069                })
2070                .ok();
2071            }
2072        });
2073
2074        self.pending_completions.push(PendingCompletion {
2075            id: pending_completion_id,
2076            assistant_message_id: assistant_message.id,
2077            _task: task,
2078        });
2079
2080        Some(user_message)
2081    }
2082
2083    pub fn to_completion_request(&self, cx: &AppContext) -> LanguageModelRequest {
2084        let buffer = self.buffer.read(cx);
2085
2086        let mut contents = self.contents(cx).peekable();
2087
2088        fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2089            let text: String = buffer.text_for_range(range.clone()).collect();
2090            if text.trim().is_empty() {
2091                None
2092            } else {
2093                Some(text)
2094            }
2095        }
2096
2097        let mut completion_request = LanguageModelRequest {
2098            messages: Vec::new(),
2099            tools: Vec::new(),
2100            stop: Vec::new(),
2101            temperature: None,
2102        };
2103        for message in self.messages(cx) {
2104            if message.status != MessageStatus::Done {
2105                continue;
2106            }
2107
2108            let mut offset = message.offset_range.start;
2109            let mut request_message = LanguageModelRequestMessage {
2110                role: message.role,
2111                content: Vec::new(),
2112                cache: message
2113                    .cache
2114                    .as_ref()
2115                    .map_or(false, |cache| cache.is_anchor),
2116            };
2117
2118            while let Some(content) = contents.peek() {
2119                if content
2120                    .range()
2121                    .end
2122                    .cmp(&message.anchor_range.end, buffer)
2123                    .is_lt()
2124                {
2125                    let content = contents.next().unwrap();
2126                    let range = content.range().to_offset(buffer);
2127                    request_message.content.extend(
2128                        collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2129                    );
2130
2131                    match content {
2132                        Content::Image { image, .. } => {
2133                            if let Some(image) = image.clone().now_or_never().flatten() {
2134                                request_message
2135                                    .content
2136                                    .push(language_model::MessageContent::Image(image));
2137                            }
2138                        }
2139                        Content::ToolUse { tool_use, .. } => {
2140                            request_message
2141                                .content
2142                                .push(language_model::MessageContent::ToolUse(tool_use.clone()));
2143                        }
2144                        Content::ToolResult { tool_use_id, .. } => {
2145                            request_message.content.push(
2146                                language_model::MessageContent::ToolResult(
2147                                    LanguageModelToolResult {
2148                                        tool_use_id: tool_use_id.to_string(),
2149                                        is_error: false,
2150                                        content: collect_text_content(buffer, range.clone())
2151                                            .unwrap_or_default(),
2152                                    },
2153                                ),
2154                            );
2155                        }
2156                    }
2157
2158                    offset = range.end;
2159                } else {
2160                    break;
2161                }
2162            }
2163
2164            request_message.content.extend(
2165                collect_text_content(buffer, offset..message.offset_range.end)
2166                    .map(MessageContent::Text),
2167            );
2168
2169            completion_request.messages.push(request_message);
2170        }
2171
2172        completion_request
2173    }
2174
2175    pub fn cancel_last_assist(&mut self, cx: &mut ModelContext<Self>) -> bool {
2176        if let Some(pending_completion) = self.pending_completions.pop() {
2177            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2178                if metadata.status == MessageStatus::Pending {
2179                    metadata.status = MessageStatus::Canceled;
2180                }
2181            });
2182            true
2183        } else {
2184            false
2185        }
2186    }
2187
2188    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
2189        for id in &ids {
2190            if let Some(metadata) = self.messages_metadata.get(id) {
2191                let role = metadata.role.cycle();
2192                self.update_metadata(*id, cx, |metadata| metadata.role = role);
2193            }
2194        }
2195
2196        self.message_roles_updated(ids, cx);
2197    }
2198
2199    fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
2200        let mut ranges = Vec::new();
2201        for message in self.messages(cx) {
2202            if ids.contains(&message.id) {
2203                ranges.push(message.anchor_range.clone());
2204            }
2205        }
2206
2207        let buffer = self.buffer.read(cx).text_snapshot();
2208        let mut updated = Vec::new();
2209        let mut removed = Vec::new();
2210        for range in ranges {
2211            self.reparse_patches_in_range(range, &buffer, &mut updated, &mut removed, cx);
2212        }
2213
2214        if !updated.is_empty() || !removed.is_empty() {
2215            cx.emit(ContextEvent::PatchesUpdated { removed, updated })
2216        }
2217    }
2218
2219    pub fn update_metadata(
2220        &mut self,
2221        id: MessageId,
2222        cx: &mut ModelContext<Self>,
2223        f: impl FnOnce(&mut MessageMetadata),
2224    ) {
2225        let version = self.version.clone();
2226        let timestamp = self.next_timestamp();
2227        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2228            f(metadata);
2229            metadata.timestamp = timestamp;
2230            let operation = ContextOperation::UpdateMessage {
2231                message_id: id,
2232                metadata: metadata.clone(),
2233                version,
2234            };
2235            self.push_op(operation, cx);
2236            cx.emit(ContextEvent::MessagesEdited);
2237            cx.notify();
2238        }
2239    }
2240
2241    pub fn insert_message_after(
2242        &mut self,
2243        message_id: MessageId,
2244        role: Role,
2245        status: MessageStatus,
2246        cx: &mut ModelContext<Self>,
2247    ) -> Option<MessageAnchor> {
2248        if let Some(prev_message_ix) = self
2249            .message_anchors
2250            .iter()
2251            .position(|message| message.id == message_id)
2252        {
2253            // Find the next valid message after the one we were given.
2254            let mut next_message_ix = prev_message_ix + 1;
2255            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2256                if next_message.start.is_valid(self.buffer.read(cx)) {
2257                    break;
2258                }
2259                next_message_ix += 1;
2260            }
2261
2262            let start = self.buffer.update(cx, |buffer, cx| {
2263                let offset = self
2264                    .message_anchors
2265                    .get(next_message_ix)
2266                    .map_or(buffer.len(), |message| {
2267                        buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
2268                    });
2269                buffer.edit([(offset..offset, "\n")], None, cx);
2270                buffer.anchor_before(offset + 1)
2271            });
2272
2273            let version = self.version.clone();
2274            let anchor = MessageAnchor {
2275                id: MessageId(self.next_timestamp()),
2276                start,
2277            };
2278            let metadata = MessageMetadata {
2279                role,
2280                status,
2281                timestamp: anchor.id.0,
2282                cache: None,
2283            };
2284            self.insert_message(anchor.clone(), metadata.clone(), cx);
2285            self.push_op(
2286                ContextOperation::InsertMessage {
2287                    anchor: anchor.clone(),
2288                    metadata,
2289                    version,
2290                },
2291                cx,
2292            );
2293            Some(anchor)
2294        } else {
2295            None
2296        }
2297    }
2298
2299    pub fn insert_content(&mut self, content: Content, cx: &mut ModelContext<Self>) {
2300        let buffer = self.buffer.read(cx);
2301        let insertion_ix = match self
2302            .contents
2303            .binary_search_by(|probe| probe.cmp(&content, buffer))
2304        {
2305            Ok(ix) => {
2306                self.contents.remove(ix);
2307                ix
2308            }
2309            Err(ix) => ix,
2310        };
2311        self.contents.insert(insertion_ix, content);
2312        cx.emit(ContextEvent::MessagesEdited);
2313    }
2314
2315    pub fn contents<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Content> {
2316        let buffer = self.buffer.read(cx);
2317        self.contents
2318            .iter()
2319            .filter(|content| {
2320                let range = content.range();
2321                range.start.is_valid(buffer) && range.end.is_valid(buffer)
2322            })
2323            .cloned()
2324    }
2325
2326    pub fn split_message(
2327        &mut self,
2328        range: Range<usize>,
2329        cx: &mut ModelContext<Self>,
2330    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2331        let start_message = self.message_for_offset(range.start, cx);
2332        let end_message = self.message_for_offset(range.end, cx);
2333        if let Some((start_message, end_message)) = start_message.zip(end_message) {
2334            // Prevent splitting when range spans multiple messages.
2335            if start_message.id != end_message.id {
2336                return (None, None);
2337            }
2338
2339            let message = start_message;
2340            let role = message.role;
2341            let mut edited_buffer = false;
2342
2343            let mut suffix_start = None;
2344
2345            // TODO: why did this start panicking?
2346            if range.start > message.offset_range.start
2347                && range.end < message.offset_range.end.saturating_sub(1)
2348            {
2349                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2350                    suffix_start = Some(range.end + 1);
2351                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2352                    suffix_start = Some(range.end);
2353                }
2354            }
2355
2356            let version = self.version.clone();
2357            let suffix = if let Some(suffix_start) = suffix_start {
2358                MessageAnchor {
2359                    id: MessageId(self.next_timestamp()),
2360                    start: self.buffer.read(cx).anchor_before(suffix_start),
2361                }
2362            } else {
2363                self.buffer.update(cx, |buffer, cx| {
2364                    buffer.edit([(range.end..range.end, "\n")], None, cx);
2365                });
2366                edited_buffer = true;
2367                MessageAnchor {
2368                    id: MessageId(self.next_timestamp()),
2369                    start: self.buffer.read(cx).anchor_before(range.end + 1),
2370                }
2371            };
2372
2373            let suffix_metadata = MessageMetadata {
2374                role,
2375                status: MessageStatus::Done,
2376                timestamp: suffix.id.0,
2377                cache: None,
2378            };
2379            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2380            self.push_op(
2381                ContextOperation::InsertMessage {
2382                    anchor: suffix.clone(),
2383                    metadata: suffix_metadata,
2384                    version,
2385                },
2386                cx,
2387            );
2388
2389            let new_messages =
2390                if range.start == range.end || range.start == message.offset_range.start {
2391                    (None, Some(suffix))
2392                } else {
2393                    let mut prefix_end = None;
2394                    if range.start > message.offset_range.start
2395                        && range.end < message.offset_range.end - 1
2396                    {
2397                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2398                            prefix_end = Some(range.start + 1);
2399                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2400                            == Some('\n')
2401                        {
2402                            prefix_end = Some(range.start);
2403                        }
2404                    }
2405
2406                    let version = self.version.clone();
2407                    let selection = if let Some(prefix_end) = prefix_end {
2408                        MessageAnchor {
2409                            id: MessageId(self.next_timestamp()),
2410                            start: self.buffer.read(cx).anchor_before(prefix_end),
2411                        }
2412                    } else {
2413                        self.buffer.update(cx, |buffer, cx| {
2414                            buffer.edit([(range.start..range.start, "\n")], None, cx)
2415                        });
2416                        edited_buffer = true;
2417                        MessageAnchor {
2418                            id: MessageId(self.next_timestamp()),
2419                            start: self.buffer.read(cx).anchor_before(range.end + 1),
2420                        }
2421                    };
2422
2423                    let selection_metadata = MessageMetadata {
2424                        role,
2425                        status: MessageStatus::Done,
2426                        timestamp: selection.id.0,
2427                        cache: None,
2428                    };
2429                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2430                    self.push_op(
2431                        ContextOperation::InsertMessage {
2432                            anchor: selection.clone(),
2433                            metadata: selection_metadata,
2434                            version,
2435                        },
2436                        cx,
2437                    );
2438
2439                    (Some(selection), Some(suffix))
2440                };
2441
2442            if !edited_buffer {
2443                cx.emit(ContextEvent::MessagesEdited);
2444            }
2445            new_messages
2446        } else {
2447            (None, None)
2448        }
2449    }
2450
2451    fn insert_message(
2452        &mut self,
2453        new_anchor: MessageAnchor,
2454        new_metadata: MessageMetadata,
2455        cx: &mut ModelContext<Self>,
2456    ) {
2457        cx.emit(ContextEvent::MessagesEdited);
2458
2459        self.messages_metadata.insert(new_anchor.id, new_metadata);
2460
2461        let buffer = self.buffer.read(cx);
2462        let insertion_ix = self
2463            .message_anchors
2464            .iter()
2465            .position(|anchor| {
2466                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2467                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2468            })
2469            .unwrap_or(self.message_anchors.len());
2470        self.message_anchors.insert(insertion_ix, new_anchor);
2471    }
2472
2473    pub(super) fn summarize(&mut self, replace_old: bool, cx: &mut ModelContext<Self>) {
2474        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
2475            return;
2476        };
2477        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
2478            return;
2479        };
2480
2481        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
2482            if !provider.is_authenticated(cx) {
2483                return;
2484            }
2485
2486            let mut request = self.to_completion_request(cx);
2487            request.messages.push(LanguageModelRequestMessage {
2488                role: Role::User,
2489                content: vec![
2490                    "Generate a concise 3-7 word title for this conversation, omitting punctuation"
2491                        .into(),
2492                ],
2493                cache: false,
2494            });
2495
2496            self.pending_summary = cx.spawn(|this, mut cx| {
2497                async move {
2498                    let stream = model.stream_completion_text(request, &cx);
2499                    let mut messages = stream.await?;
2500
2501                    let mut replaced = !replace_old;
2502                    while let Some(message) = messages.next().await {
2503                        let text = message?;
2504                        let mut lines = text.lines();
2505                        this.update(&mut cx, |this, cx| {
2506                            let version = this.version.clone();
2507                            let timestamp = this.next_timestamp();
2508                            let summary = this.summary.get_or_insert(ContextSummary::default());
2509                            if !replaced && replace_old {
2510                                summary.text.clear();
2511                                replaced = true;
2512                            }
2513                            summary.text.extend(lines.next());
2514                            summary.timestamp = timestamp;
2515                            let operation = ContextOperation::UpdateSummary {
2516                                summary: summary.clone(),
2517                                version,
2518                            };
2519                            this.push_op(operation, cx);
2520                            cx.emit(ContextEvent::SummaryChanged);
2521                        })?;
2522
2523                        // Stop if the LLM generated multiple lines.
2524                        if lines.next().is_some() {
2525                            break;
2526                        }
2527                    }
2528
2529                    this.update(&mut cx, |this, cx| {
2530                        let version = this.version.clone();
2531                        let timestamp = this.next_timestamp();
2532                        if let Some(summary) = this.summary.as_mut() {
2533                            summary.done = true;
2534                            summary.timestamp = timestamp;
2535                            let operation = ContextOperation::UpdateSummary {
2536                                summary: summary.clone(),
2537                                version,
2538                            };
2539                            this.push_op(operation, cx);
2540                            cx.emit(ContextEvent::SummaryChanged);
2541                        }
2542                    })?;
2543
2544                    anyhow::Ok(())
2545                }
2546                .log_err()
2547            });
2548        }
2549    }
2550
2551    fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
2552        self.messages_for_offsets([offset], cx).pop()
2553    }
2554
2555    pub fn messages_for_offsets(
2556        &self,
2557        offsets: impl IntoIterator<Item = usize>,
2558        cx: &AppContext,
2559    ) -> Vec<Message> {
2560        let mut result = Vec::new();
2561
2562        let mut messages = self.messages(cx).peekable();
2563        let mut offsets = offsets.into_iter().peekable();
2564        let mut current_message = messages.next();
2565        while let Some(offset) = offsets.next() {
2566            // Locate the message that contains the offset.
2567            while current_message.as_ref().map_or(false, |message| {
2568                !message.offset_range.contains(&offset) && messages.peek().is_some()
2569            }) {
2570                current_message = messages.next();
2571            }
2572            let Some(message) = current_message.as_ref() else {
2573                break;
2574            };
2575
2576            // Skip offsets that are in the same message.
2577            while offsets.peek().map_or(false, |offset| {
2578                message.offset_range.contains(offset) || messages.peek().is_none()
2579            }) {
2580                offsets.next();
2581            }
2582
2583            result.push(message.clone());
2584        }
2585        result
2586    }
2587
2588    fn messages_from_anchors<'a>(
2589        &'a self,
2590        message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2591        cx: &'a AppContext,
2592    ) -> impl 'a + Iterator<Item = Message> {
2593        let buffer = self.buffer.read(cx);
2594
2595        Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2596    }
2597
2598    pub fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
2599        self.messages_from_anchors(self.message_anchors.iter(), cx)
2600    }
2601
2602    pub fn messages_from_iters<'a>(
2603        buffer: &'a Buffer,
2604        metadata: &'a HashMap<MessageId, MessageMetadata>,
2605        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2606    ) -> impl 'a + Iterator<Item = Message> {
2607        let mut messages = messages.peekable();
2608
2609        iter::from_fn(move || {
2610            if let Some((start_ix, message_anchor)) = messages.next() {
2611                let metadata = metadata.get(&message_anchor.id)?;
2612
2613                let message_start = message_anchor.start.to_offset(buffer);
2614                let mut message_end = None;
2615                let mut end_ix = start_ix;
2616                while let Some((_, next_message)) = messages.peek() {
2617                    if next_message.start.is_valid(buffer) {
2618                        message_end = Some(next_message.start);
2619                        break;
2620                    } else {
2621                        end_ix += 1;
2622                        messages.next();
2623                    }
2624                }
2625                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2626                let message_end = message_end_anchor.to_offset(buffer);
2627
2628                return Some(Message {
2629                    index_range: start_ix..end_ix,
2630                    offset_range: message_start..message_end,
2631                    anchor_range: message_anchor.start..message_end_anchor,
2632                    id: message_anchor.id,
2633                    role: metadata.role,
2634                    status: metadata.status.clone(),
2635                    cache: metadata.cache.clone(),
2636                });
2637            }
2638            None
2639        })
2640    }
2641
2642    pub fn save(
2643        &mut self,
2644        debounce: Option<Duration>,
2645        fs: Arc<dyn Fs>,
2646        cx: &mut ModelContext<Context>,
2647    ) {
2648        if self.replica_id() != ReplicaId::default() {
2649            // Prevent saving a remote context for now.
2650            return;
2651        }
2652
2653        self.pending_save = cx.spawn(|this, mut cx| async move {
2654            if let Some(debounce) = debounce {
2655                cx.background_executor().timer(debounce).await;
2656            }
2657
2658            let (old_path, summary) = this.read_with(&cx, |this, _| {
2659                let path = this.path.clone();
2660                let summary = if let Some(summary) = this.summary.as_ref() {
2661                    if summary.done {
2662                        Some(summary.text.clone())
2663                    } else {
2664                        None
2665                    }
2666                } else {
2667                    None
2668                };
2669                (path, summary)
2670            })?;
2671
2672            if let Some(summary) = summary {
2673                let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2674                let mut discriminant = 1;
2675                let mut new_path;
2676                loop {
2677                    new_path = contexts_dir().join(&format!(
2678                        "{} - {}.zed.json",
2679                        summary.trim(),
2680                        discriminant
2681                    ));
2682                    if fs.is_file(&new_path).await {
2683                        discriminant += 1;
2684                    } else {
2685                        break;
2686                    }
2687                }
2688
2689                fs.create_dir(contexts_dir().as_ref()).await?;
2690                fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
2691                    .await?;
2692                if let Some(old_path) = old_path {
2693                    if new_path != old_path {
2694                        fs.remove_file(
2695                            &old_path,
2696                            RemoveOptions {
2697                                recursive: false,
2698                                ignore_if_not_exists: true,
2699                            },
2700                        )
2701                        .await?;
2702                    }
2703                }
2704
2705                this.update(&mut cx, |this, _| this.path = Some(new_path))?;
2706            }
2707
2708            Ok(())
2709        });
2710    }
2711
2712    pub(crate) fn custom_summary(&mut self, custom_summary: String, cx: &mut ModelContext<Self>) {
2713        let timestamp = self.next_timestamp();
2714        let summary = self.summary.get_or_insert(ContextSummary::default());
2715        summary.timestamp = timestamp;
2716        summary.done = true;
2717        summary.text = custom_summary;
2718        cx.emit(ContextEvent::SummaryChanged);
2719    }
2720}
2721
2722fn trimmed_text_in_range(buffer: &BufferSnapshot, range: Range<text::Anchor>) -> String {
2723    let mut is_start = true;
2724    let mut content = buffer
2725        .text_for_range(range)
2726        .map(|mut chunk| {
2727            if is_start {
2728                chunk = chunk.trim_start_matches('\n');
2729                if !chunk.is_empty() {
2730                    is_start = false;
2731                }
2732            }
2733            chunk
2734        })
2735        .collect::<String>();
2736    content.truncate(content.trim_end().len());
2737    content
2738}
2739
2740#[derive(Debug, Default)]
2741pub struct ContextVersion {
2742    context: clock::Global,
2743    buffer: clock::Global,
2744}
2745
2746impl ContextVersion {
2747    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2748        Self {
2749            context: language::proto::deserialize_version(&proto.context_version),
2750            buffer: language::proto::deserialize_version(&proto.buffer_version),
2751        }
2752    }
2753
2754    pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
2755        proto::ContextVersion {
2756            context_id: context_id.to_proto(),
2757            context_version: language::proto::serialize_version(&self.context),
2758            buffer_version: language::proto::serialize_version(&self.buffer),
2759        }
2760    }
2761}
2762
2763#[derive(Debug, Clone)]
2764pub struct PendingSlashCommand {
2765    pub name: String,
2766    pub arguments: SmallVec<[String; 3]>,
2767    pub status: PendingSlashCommandStatus,
2768    pub source_range: Range<language::Anchor>,
2769}
2770
2771#[derive(Debug, Clone)]
2772pub enum PendingSlashCommandStatus {
2773    Idle,
2774    Running { _task: Shared<Task<()>> },
2775    Error(String),
2776}
2777
2778pub(crate) struct ToolUseFeatureFlag;
2779
2780impl FeatureFlag for ToolUseFeatureFlag {
2781    const NAME: &'static str = "assistant-tool-use";
2782
2783    fn enabled_for_staff() -> bool {
2784        false
2785    }
2786}
2787
2788#[derive(Debug, Clone)]
2789pub struct PendingToolUse {
2790    pub id: Arc<str>,
2791    pub name: String,
2792    pub input: serde_json::Value,
2793    pub status: PendingToolUseStatus,
2794    pub source_range: Range<language::Anchor>,
2795}
2796
2797#[derive(Debug, Clone)]
2798pub enum PendingToolUseStatus {
2799    Idle,
2800    Running { _task: Shared<Task<()>> },
2801    Error(String),
2802}
2803
2804impl PendingToolUseStatus {
2805    pub fn is_idle(&self) -> bool {
2806        matches!(self, PendingToolUseStatus::Idle)
2807    }
2808}
2809
2810#[derive(Serialize, Deserialize)]
2811pub struct SavedMessage {
2812    pub id: MessageId,
2813    pub start: usize,
2814    pub metadata: MessageMetadata,
2815}
2816
2817#[derive(Serialize, Deserialize)]
2818pub struct SavedContext {
2819    pub id: Option<ContextId>,
2820    pub zed: String,
2821    pub version: String,
2822    pub text: String,
2823    pub messages: Vec<SavedMessage>,
2824    pub summary: String,
2825    pub slash_command_output_sections:
2826        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2827}
2828
2829impl SavedContext {
2830    pub const VERSION: &'static str = "0.4.0";
2831
2832    pub fn from_json(json: &str) -> Result<Self> {
2833        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
2834        match saved_context_json
2835            .get("version")
2836            .ok_or_else(|| anyhow!("version not found"))?
2837        {
2838            serde_json::Value::String(version) => match version.as_str() {
2839                SavedContext::VERSION => {
2840                    Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
2841                }
2842                SavedContextV0_3_0::VERSION => {
2843                    let saved_context =
2844                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
2845                    Ok(saved_context.upgrade())
2846                }
2847                SavedContextV0_2_0::VERSION => {
2848                    let saved_context =
2849                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
2850                    Ok(saved_context.upgrade())
2851                }
2852                SavedContextV0_1_0::VERSION => {
2853                    let saved_context =
2854                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
2855                    Ok(saved_context.upgrade())
2856                }
2857                _ => Err(anyhow!("unrecognized saved context version: {}", version)),
2858            },
2859            _ => Err(anyhow!("version not found on saved context")),
2860        }
2861    }
2862
2863    fn into_ops(
2864        self,
2865        buffer: &Model<Buffer>,
2866        cx: &mut ModelContext<Context>,
2867    ) -> Vec<ContextOperation> {
2868        let mut operations = Vec::new();
2869        let mut version = clock::Global::new();
2870        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
2871
2872        let mut first_message_metadata = None;
2873        for message in self.messages {
2874            if message.id == MessageId(clock::Lamport::default()) {
2875                first_message_metadata = Some(message.metadata);
2876            } else {
2877                operations.push(ContextOperation::InsertMessage {
2878                    anchor: MessageAnchor {
2879                        id: message.id,
2880                        start: buffer.read(cx).anchor_before(message.start),
2881                    },
2882                    metadata: MessageMetadata {
2883                        role: message.metadata.role,
2884                        status: message.metadata.status,
2885                        timestamp: message.metadata.timestamp,
2886                        cache: None,
2887                    },
2888                    version: version.clone(),
2889                });
2890                version.observe(message.id.0);
2891                next_timestamp.observe(message.id.0);
2892            }
2893        }
2894
2895        if let Some(metadata) = first_message_metadata {
2896            let timestamp = next_timestamp.tick();
2897            operations.push(ContextOperation::UpdateMessage {
2898                message_id: MessageId(clock::Lamport::default()),
2899                metadata: MessageMetadata {
2900                    role: metadata.role,
2901                    status: metadata.status,
2902                    timestamp,
2903                    cache: None,
2904                },
2905                version: version.clone(),
2906            });
2907            version.observe(timestamp);
2908        }
2909
2910        let timestamp = next_timestamp.tick();
2911        operations.push(ContextOperation::SlashCommandFinished {
2912            id: SlashCommandId(timestamp),
2913            output_range: language::Anchor::MIN..language::Anchor::MAX,
2914            sections: self
2915                .slash_command_output_sections
2916                .into_iter()
2917                .map(|section| {
2918                    let buffer = buffer.read(cx);
2919                    SlashCommandOutputSection {
2920                        range: buffer.anchor_after(section.range.start)
2921                            ..buffer.anchor_before(section.range.end),
2922                        icon: section.icon,
2923                        label: section.label,
2924                        metadata: section.metadata,
2925                    }
2926                })
2927                .collect(),
2928            version: version.clone(),
2929        });
2930        version.observe(timestamp);
2931
2932        let timestamp = next_timestamp.tick();
2933        operations.push(ContextOperation::UpdateSummary {
2934            summary: ContextSummary {
2935                text: self.summary,
2936                done: true,
2937                timestamp,
2938            },
2939            version: version.clone(),
2940        });
2941        version.observe(timestamp);
2942
2943        operations
2944    }
2945}
2946
2947#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
2948struct SavedMessageIdPreV0_4_0(usize);
2949
2950#[derive(Serialize, Deserialize)]
2951struct SavedMessagePreV0_4_0 {
2952    id: SavedMessageIdPreV0_4_0,
2953    start: usize,
2954}
2955
2956#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2957struct SavedMessageMetadataPreV0_4_0 {
2958    role: Role,
2959    status: MessageStatus,
2960}
2961
2962#[derive(Serialize, Deserialize)]
2963struct SavedContextV0_3_0 {
2964    id: Option<ContextId>,
2965    zed: String,
2966    version: String,
2967    text: String,
2968    messages: Vec<SavedMessagePreV0_4_0>,
2969    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2970    summary: String,
2971    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2972}
2973
2974impl SavedContextV0_3_0 {
2975    const VERSION: &'static str = "0.3.0";
2976
2977    fn upgrade(self) -> SavedContext {
2978        SavedContext {
2979            id: self.id,
2980            zed: self.zed,
2981            version: SavedContext::VERSION.into(),
2982            text: self.text,
2983            messages: self
2984                .messages
2985                .into_iter()
2986                .filter_map(|message| {
2987                    let metadata = self.message_metadata.get(&message.id)?;
2988                    let timestamp = clock::Lamport {
2989                        replica_id: ReplicaId::default(),
2990                        value: message.id.0 as u32,
2991                    };
2992                    Some(SavedMessage {
2993                        id: MessageId(timestamp),
2994                        start: message.start,
2995                        metadata: MessageMetadata {
2996                            role: metadata.role,
2997                            status: metadata.status.clone(),
2998                            timestamp,
2999                            cache: None,
3000                        },
3001                    })
3002                })
3003                .collect(),
3004            summary: self.summary,
3005            slash_command_output_sections: self.slash_command_output_sections,
3006        }
3007    }
3008}
3009
3010#[derive(Serialize, Deserialize)]
3011struct SavedContextV0_2_0 {
3012    id: Option<ContextId>,
3013    zed: String,
3014    version: String,
3015    text: String,
3016    messages: Vec<SavedMessagePreV0_4_0>,
3017    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3018    summary: String,
3019}
3020
3021impl SavedContextV0_2_0 {
3022    const VERSION: &'static str = "0.2.0";
3023
3024    fn upgrade(self) -> SavedContext {
3025        SavedContextV0_3_0 {
3026            id: self.id,
3027            zed: self.zed,
3028            version: SavedContextV0_3_0::VERSION.to_string(),
3029            text: self.text,
3030            messages: self.messages,
3031            message_metadata: self.message_metadata,
3032            summary: self.summary,
3033            slash_command_output_sections: Vec::new(),
3034        }
3035        .upgrade()
3036    }
3037}
3038
3039#[derive(Serialize, Deserialize)]
3040struct SavedContextV0_1_0 {
3041    id: Option<ContextId>,
3042    zed: String,
3043    version: String,
3044    text: String,
3045    messages: Vec<SavedMessagePreV0_4_0>,
3046    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3047    summary: String,
3048    api_url: Option<String>,
3049    model: OpenAiModel,
3050}
3051
3052impl SavedContextV0_1_0 {
3053    const VERSION: &'static str = "0.1.0";
3054
3055    fn upgrade(self) -> SavedContext {
3056        SavedContextV0_2_0 {
3057            id: self.id,
3058            zed: self.zed,
3059            version: SavedContextV0_2_0::VERSION.to_string(),
3060            text: self.text,
3061            messages: self.messages,
3062            message_metadata: self.message_metadata,
3063            summary: self.summary,
3064        }
3065        .upgrade()
3066    }
3067}
3068
3069#[derive(Clone)]
3070pub struct SavedContextMetadata {
3071    pub title: String,
3072    pub path: PathBuf,
3073    pub mtime: chrono::DateTime<chrono::Local>,
3074}