context.rs

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