assistant_context.rs

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