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