context.rs

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