context.rs

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