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