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::RedactedThinking { .. } => {},
2114                                    LanguageModelCompletionEvent::Text(mut chunk) => {
2115                                        if let Some(start) = thought_process_stack.pop() {
2116                                            let end = buffer.anchor_before(message_old_end_offset);
2117                                            context_event =
2118                                                Some(ContextEvent::EndedThoughtProcess(end));
2119                                            thought_process_output_section =
2120                                                Some(ThoughtProcessOutputSection {
2121                                                    range: start..end,
2122                                                });
2123                                            chunk.insert_str(0, "\n\n");
2124                                        }
2125
2126                                        buffer.edit(
2127                                            [(
2128                                                message_old_end_offset..message_old_end_offset,
2129                                                chunk,
2130                                            )],
2131                                            None,
2132                                            cx,
2133                                        );
2134                                    }
2135                                    LanguageModelCompletionEvent::ToolUse(_) |
2136                                    LanguageModelCompletionEvent::UsageUpdate(_)  => {}
2137                                }
2138                            });
2139
2140                            if let Some(section) = thought_process_output_section.take() {
2141                                this.insert_thought_process_output_section(section, cx);
2142                            }
2143                            if let Some(context_event) = context_event.take() {
2144                                cx.emit(context_event);
2145                            }
2146
2147                            cx.emit(ContextEvent::StreamedCompletion);
2148
2149                            Some(())
2150                        })?;
2151                        smol::future::yield_now().await;
2152                    }
2153                    this.update(cx, |this, cx| {
2154                        this.pending_completions
2155                            .retain(|completion| completion.id != pending_completion_id);
2156                        this.summarize(false, cx);
2157                        this.update_cache_status_for_completion(cx);
2158                    })?;
2159
2160                    anyhow::Ok(stop_reason)
2161                };
2162
2163                let result = stream_completion.await;
2164
2165                this.update(cx, |this, cx| {
2166                    let error_message = if let Some(error) = result.as_ref().err() {
2167                        if error.is::<PaymentRequiredError>() {
2168                            cx.emit(ContextEvent::ShowPaymentRequiredError);
2169                            this.update_metadata(assistant_message_id, cx, |metadata| {
2170                                metadata.status = MessageStatus::Canceled;
2171                            });
2172                            Some(error.to_string())
2173                        } else {
2174                            let error_message = error
2175                                .chain()
2176                                .map(|err| err.to_string())
2177                                .collect::<Vec<_>>()
2178                                .join("\n");
2179                            cx.emit(ContextEvent::ShowAssistError(SharedString::from(
2180                                error_message.clone(),
2181                            )));
2182                            this.update_metadata(assistant_message_id, cx, |metadata| {
2183                                metadata.status =
2184                                    MessageStatus::Error(SharedString::from(error_message.clone()));
2185                            });
2186                            Some(error_message)
2187                        }
2188                    } else {
2189                        this.update_metadata(assistant_message_id, cx, |metadata| {
2190                            metadata.status = MessageStatus::Done;
2191                        });
2192                        None
2193                    };
2194
2195                    let language_name = this
2196                        .buffer
2197                        .read(cx)
2198                        .language()
2199                        .map(|language| language.name());
2200                    report_assistant_event(
2201                        AssistantEventData {
2202                            conversation_id: Some(this.id.0.clone()),
2203                            kind: AssistantKind::Panel,
2204                            phase: AssistantPhase::Response,
2205                            message_id: None,
2206                            model: model.telemetry_id(),
2207                            model_provider: model.provider_id().to_string(),
2208                            response_latency,
2209                            error_message,
2210                            language_name: language_name.map(|name| name.to_proto()),
2211                        },
2212                        this.telemetry.clone(),
2213                        cx.http_client(),
2214                        model.api_key(cx),
2215                        cx.background_executor(),
2216                    );
2217
2218                    if let Ok(stop_reason) = result {
2219                        match stop_reason {
2220                            StopReason::ToolUse => {}
2221                            StopReason::EndTurn => {}
2222                            StopReason::MaxTokens => {}
2223                            StopReason::Refusal => {}
2224                        }
2225                    }
2226                })
2227                .ok();
2228            }
2229        });
2230
2231        self.pending_completions.push(PendingCompletion {
2232            id: pending_completion_id,
2233            assistant_message_id: assistant_message.id,
2234            _task: task,
2235        });
2236
2237        Some(user_message)
2238    }
2239
2240    pub fn to_xml(&self, cx: &App) -> String {
2241        let mut output = String::new();
2242        let buffer = self.buffer.read(cx);
2243        for message in self.messages(cx) {
2244            if message.status != MessageStatus::Done {
2245                continue;
2246            }
2247
2248            writeln!(&mut output, "<{}>", message.role).unwrap();
2249            for chunk in buffer.text_for_range(message.offset_range) {
2250                output.push_str(chunk);
2251            }
2252            if !output.ends_with('\n') {
2253                output.push('\n');
2254            }
2255            writeln!(&mut output, "</{}>", message.role).unwrap();
2256        }
2257        output
2258    }
2259
2260    pub fn to_completion_request(
2261        &self,
2262        model: Option<&Arc<dyn LanguageModel>>,
2263        cx: &App,
2264    ) -> LanguageModelRequest {
2265        let buffer = self.buffer.read(cx);
2266
2267        let mut contents = self.contents(cx).peekable();
2268
2269        fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2270            let text: String = buffer.text_for_range(range.clone()).collect();
2271            if text.trim().is_empty() {
2272                None
2273            } else {
2274                Some(text)
2275            }
2276        }
2277
2278        let mut completion_request = LanguageModelRequest {
2279            thread_id: None,
2280            prompt_id: None,
2281            intent: Some(CompletionIntent::UserPrompt),
2282            mode: None,
2283            messages: Vec::new(),
2284            tools: Vec::new(),
2285            tool_choice: None,
2286            stop: Vec::new(),
2287            temperature: model.and_then(|model| AgentSettings::temperature_for_model(model, cx)),
2288        };
2289        for message in self.messages(cx) {
2290            if message.status != MessageStatus::Done {
2291                continue;
2292            }
2293
2294            let mut offset = message.offset_range.start;
2295            let mut request_message = LanguageModelRequestMessage {
2296                role: message.role,
2297                content: Vec::new(),
2298                cache: message
2299                    .cache
2300                    .as_ref()
2301                    .map_or(false, |cache| cache.is_anchor),
2302            };
2303
2304            while let Some(content) = contents.peek() {
2305                if content
2306                    .range()
2307                    .end
2308                    .cmp(&message.anchor_range.end, buffer)
2309                    .is_lt()
2310                {
2311                    let content = contents.next().unwrap();
2312                    let range = content.range().to_offset(buffer);
2313                    request_message.content.extend(
2314                        collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2315                    );
2316
2317                    match content {
2318                        Content::Image { image, .. } => {
2319                            if let Some(image) = image.clone().now_or_never().flatten() {
2320                                request_message
2321                                    .content
2322                                    .push(language_model::MessageContent::Image(image));
2323                            }
2324                        }
2325                    }
2326
2327                    offset = range.end;
2328                } else {
2329                    break;
2330                }
2331            }
2332
2333            request_message.content.extend(
2334                collect_text_content(buffer, offset..message.offset_range.end)
2335                    .map(MessageContent::Text),
2336            );
2337
2338            if !request_message.contents_empty() {
2339                completion_request.messages.push(request_message);
2340            }
2341        }
2342        let supports_max_mode = if let Some(model) = model {
2343            model.supports_max_mode()
2344        } else {
2345            false
2346        };
2347
2348        if supports_max_mode {
2349            completion_request.mode = Some(self.completion_mode.into());
2350        }
2351        completion_request
2352    }
2353
2354    pub fn cancel_last_assist(&mut self, cx: &mut Context<Self>) -> bool {
2355        if let Some(pending_completion) = self.pending_completions.pop() {
2356            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2357                if metadata.status == MessageStatus::Pending {
2358                    metadata.status = MessageStatus::Canceled;
2359                }
2360            });
2361            true
2362        } else {
2363            false
2364        }
2365    }
2366
2367    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2368        for id in &ids {
2369            if let Some(metadata) = self.messages_metadata.get(id) {
2370                let role = metadata.role.cycle();
2371                self.update_metadata(*id, cx, |metadata| metadata.role = role);
2372            }
2373        }
2374
2375        self.message_roles_updated(ids, cx);
2376    }
2377
2378    fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2379        let mut ranges = Vec::new();
2380        for message in self.messages(cx) {
2381            if ids.contains(&message.id) {
2382                ranges.push(message.anchor_range.clone());
2383            }
2384        }
2385    }
2386
2387    pub fn update_metadata(
2388        &mut self,
2389        id: MessageId,
2390        cx: &mut Context<Self>,
2391        f: impl FnOnce(&mut MessageMetadata),
2392    ) {
2393        let version = self.version.clone();
2394        let timestamp = self.next_timestamp();
2395        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2396            f(metadata);
2397            metadata.timestamp = timestamp;
2398            let operation = ContextOperation::UpdateMessage {
2399                message_id: id,
2400                metadata: metadata.clone(),
2401                version,
2402            };
2403            self.push_op(operation, cx);
2404            cx.emit(ContextEvent::MessagesEdited);
2405            cx.notify();
2406        }
2407    }
2408
2409    pub fn insert_message_after(
2410        &mut self,
2411        message_id: MessageId,
2412        role: Role,
2413        status: MessageStatus,
2414        cx: &mut Context<Self>,
2415    ) -> Option<MessageAnchor> {
2416        if let Some(prev_message_ix) = self
2417            .message_anchors
2418            .iter()
2419            .position(|message| message.id == message_id)
2420        {
2421            // Find the next valid message after the one we were given.
2422            let mut next_message_ix = prev_message_ix + 1;
2423            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2424                if next_message.start.is_valid(self.buffer.read(cx)) {
2425                    break;
2426                }
2427                next_message_ix += 1;
2428            }
2429
2430            let buffer = self.buffer.read(cx);
2431            let offset = self
2432                .message_anchors
2433                .get(next_message_ix)
2434                .map_or(buffer.len(), |message| {
2435                    buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
2436                });
2437            Some(self.insert_message_at_offset(offset, role, status, cx))
2438        } else {
2439            None
2440        }
2441    }
2442
2443    fn insert_message_at_offset(
2444        &mut self,
2445        offset: usize,
2446        role: Role,
2447        status: MessageStatus,
2448        cx: &mut Context<Self>,
2449    ) -> MessageAnchor {
2450        let start = self.buffer.update(cx, |buffer, cx| {
2451            buffer.edit([(offset..offset, "\n")], None, cx);
2452            buffer.anchor_before(offset + 1)
2453        });
2454
2455        let version = self.version.clone();
2456        let anchor = MessageAnchor {
2457            id: MessageId(self.next_timestamp()),
2458            start,
2459        };
2460        let metadata = MessageMetadata {
2461            role,
2462            status,
2463            timestamp: anchor.id.0,
2464            cache: None,
2465        };
2466        self.insert_message(anchor.clone(), metadata.clone(), cx);
2467        self.push_op(
2468            ContextOperation::InsertMessage {
2469                anchor: anchor.clone(),
2470                metadata,
2471                version,
2472            },
2473            cx,
2474        );
2475        anchor
2476    }
2477
2478    pub fn insert_content(&mut self, content: Content, cx: &mut Context<Self>) {
2479        let buffer = self.buffer.read(cx);
2480        let insertion_ix = match self
2481            .contents
2482            .binary_search_by(|probe| probe.cmp(&content, buffer))
2483        {
2484            Ok(ix) => {
2485                self.contents.remove(ix);
2486                ix
2487            }
2488            Err(ix) => ix,
2489        };
2490        self.contents.insert(insertion_ix, content);
2491        cx.emit(ContextEvent::MessagesEdited);
2492    }
2493
2494    pub fn contents<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Content> {
2495        let buffer = self.buffer.read(cx);
2496        self.contents
2497            .iter()
2498            .filter(|content| {
2499                let range = content.range();
2500                range.start.is_valid(buffer) && range.end.is_valid(buffer)
2501            })
2502            .cloned()
2503    }
2504
2505    pub fn split_message(
2506        &mut self,
2507        range: Range<usize>,
2508        cx: &mut Context<Self>,
2509    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2510        let start_message = self.message_for_offset(range.start, cx);
2511        let end_message = self.message_for_offset(range.end, cx);
2512        if let Some((start_message, end_message)) = start_message.zip(end_message) {
2513            // Prevent splitting when range spans multiple messages.
2514            if start_message.id != end_message.id {
2515                return (None, None);
2516            }
2517
2518            let message = start_message;
2519            let role = message.role;
2520            let mut edited_buffer = false;
2521
2522            let mut suffix_start = None;
2523
2524            // TODO: why did this start panicking?
2525            if range.start > message.offset_range.start
2526                && range.end < message.offset_range.end.saturating_sub(1)
2527            {
2528                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2529                    suffix_start = Some(range.end + 1);
2530                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2531                    suffix_start = Some(range.end);
2532                }
2533            }
2534
2535            let version = self.version.clone();
2536            let suffix = if let Some(suffix_start) = suffix_start {
2537                MessageAnchor {
2538                    id: MessageId(self.next_timestamp()),
2539                    start: self.buffer.read(cx).anchor_before(suffix_start),
2540                }
2541            } else {
2542                self.buffer.update(cx, |buffer, cx| {
2543                    buffer.edit([(range.end..range.end, "\n")], None, cx);
2544                });
2545                edited_buffer = true;
2546                MessageAnchor {
2547                    id: MessageId(self.next_timestamp()),
2548                    start: self.buffer.read(cx).anchor_before(range.end + 1),
2549                }
2550            };
2551
2552            let suffix_metadata = MessageMetadata {
2553                role,
2554                status: MessageStatus::Done,
2555                timestamp: suffix.id.0,
2556                cache: None,
2557            };
2558            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2559            self.push_op(
2560                ContextOperation::InsertMessage {
2561                    anchor: suffix.clone(),
2562                    metadata: suffix_metadata,
2563                    version,
2564                },
2565                cx,
2566            );
2567
2568            let new_messages =
2569                if range.start == range.end || range.start == message.offset_range.start {
2570                    (None, Some(suffix))
2571                } else {
2572                    let mut prefix_end = None;
2573                    if range.start > message.offset_range.start
2574                        && range.end < message.offset_range.end - 1
2575                    {
2576                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2577                            prefix_end = Some(range.start + 1);
2578                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2579                            == Some('\n')
2580                        {
2581                            prefix_end = Some(range.start);
2582                        }
2583                    }
2584
2585                    let version = self.version.clone();
2586                    let selection = if let Some(prefix_end) = prefix_end {
2587                        MessageAnchor {
2588                            id: MessageId(self.next_timestamp()),
2589                            start: self.buffer.read(cx).anchor_before(prefix_end),
2590                        }
2591                    } else {
2592                        self.buffer.update(cx, |buffer, cx| {
2593                            buffer.edit([(range.start..range.start, "\n")], None, cx)
2594                        });
2595                        edited_buffer = true;
2596                        MessageAnchor {
2597                            id: MessageId(self.next_timestamp()),
2598                            start: self.buffer.read(cx).anchor_before(range.end + 1),
2599                        }
2600                    };
2601
2602                    let selection_metadata = MessageMetadata {
2603                        role,
2604                        status: MessageStatus::Done,
2605                        timestamp: selection.id.0,
2606                        cache: None,
2607                    };
2608                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2609                    self.push_op(
2610                        ContextOperation::InsertMessage {
2611                            anchor: selection.clone(),
2612                            metadata: selection_metadata,
2613                            version,
2614                        },
2615                        cx,
2616                    );
2617
2618                    (Some(selection), Some(suffix))
2619                };
2620
2621            if !edited_buffer {
2622                cx.emit(ContextEvent::MessagesEdited);
2623            }
2624            new_messages
2625        } else {
2626            (None, None)
2627        }
2628    }
2629
2630    fn insert_message(
2631        &mut self,
2632        new_anchor: MessageAnchor,
2633        new_metadata: MessageMetadata,
2634        cx: &mut Context<Self>,
2635    ) {
2636        cx.emit(ContextEvent::MessagesEdited);
2637
2638        self.messages_metadata.insert(new_anchor.id, new_metadata);
2639
2640        let buffer = self.buffer.read(cx);
2641        let insertion_ix = self
2642            .message_anchors
2643            .iter()
2644            .position(|anchor| {
2645                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2646                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2647            })
2648            .unwrap_or(self.message_anchors.len());
2649        self.message_anchors.insert(insertion_ix, new_anchor);
2650    }
2651
2652    pub fn summarize(&mut self, mut replace_old: bool, cx: &mut Context<Self>) {
2653        let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
2654            return;
2655        };
2656
2657        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_pending()) {
2658            if !model.provider.is_authenticated(cx) {
2659                return;
2660            }
2661
2662            let mut request = self.to_completion_request(Some(&model.model), cx);
2663            request.messages.push(LanguageModelRequestMessage {
2664                role: Role::User,
2665                content: vec![
2666                    "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:`"
2667                        .into(),
2668                ],
2669                cache: false,
2670            });
2671
2672            // If there is no summary, it is set with `done: false` so that "Loading Summary…" can
2673            // be displayed.
2674            match self.summary {
2675                ContextSummary::Pending | ContextSummary::Error => {
2676                    self.summary = ContextSummary::Content(ContextSummaryContent {
2677                        text: "".to_string(),
2678                        done: false,
2679                        timestamp: clock::Lamport::default(),
2680                    });
2681                    replace_old = true;
2682                }
2683                ContextSummary::Content(_) => {}
2684            }
2685
2686            self.summary_task = cx.spawn(async move |this, cx| {
2687                let result = async {
2688                    let stream = model.model.stream_completion_text(request, &cx);
2689                    let mut messages = stream.await?;
2690
2691                    let mut replaced = !replace_old;
2692                    while let Some(message) = messages.stream.next().await {
2693                        let text = message?;
2694                        let mut lines = text.lines();
2695                        this.update(cx, |this, cx| {
2696                            let version = this.version.clone();
2697                            let timestamp = this.next_timestamp();
2698                            let summary = this.summary.content_or_set_empty();
2699                            if !replaced && replace_old {
2700                                summary.text.clear();
2701                                replaced = true;
2702                            }
2703                            summary.text.extend(lines.next());
2704                            summary.timestamp = timestamp;
2705                            let operation = ContextOperation::UpdateSummary {
2706                                summary: summary.clone(),
2707                                version,
2708                            };
2709                            this.push_op(operation, cx);
2710                            cx.emit(ContextEvent::SummaryChanged);
2711                            cx.emit(ContextEvent::SummaryGenerated);
2712                        })?;
2713
2714                        // Stop if the LLM generated multiple lines.
2715                        if lines.next().is_some() {
2716                            break;
2717                        }
2718                    }
2719
2720                    this.read_with(cx, |this, _cx| {
2721                        if let Some(summary) = this.summary.content() {
2722                            if summary.text.is_empty() {
2723                                bail!("Model generated an empty summary");
2724                            }
2725                        }
2726                        Ok(())
2727                    })??;
2728
2729                    this.update(cx, |this, cx| {
2730                        let version = this.version.clone();
2731                        let timestamp = this.next_timestamp();
2732                        if let Some(summary) = this.summary.content_as_mut() {
2733                            summary.done = true;
2734                            summary.timestamp = timestamp;
2735                            let operation = ContextOperation::UpdateSummary {
2736                                summary: summary.clone(),
2737                                version,
2738                            };
2739                            this.push_op(operation, cx);
2740                            cx.emit(ContextEvent::SummaryChanged);
2741                            cx.emit(ContextEvent::SummaryGenerated);
2742                        }
2743                    })?;
2744
2745                    anyhow::Ok(())
2746                }
2747                .await;
2748
2749                if let Err(err) = result {
2750                    this.update(cx, |this, cx| {
2751                        this.summary = ContextSummary::Error;
2752                        cx.emit(ContextEvent::SummaryChanged);
2753                    })
2754                    .log_err();
2755                    log::error!("Error generating context summary: {}", err);
2756                }
2757
2758                Some(())
2759            });
2760        }
2761    }
2762
2763    fn message_for_offset(&self, offset: usize, cx: &App) -> Option<Message> {
2764        self.messages_for_offsets([offset], cx).pop()
2765    }
2766
2767    pub fn messages_for_offsets(
2768        &self,
2769        offsets: impl IntoIterator<Item = usize>,
2770        cx: &App,
2771    ) -> Vec<Message> {
2772        let mut result = Vec::new();
2773
2774        let mut messages = self.messages(cx).peekable();
2775        let mut offsets = offsets.into_iter().peekable();
2776        let mut current_message = messages.next();
2777        while let Some(offset) = offsets.next() {
2778            // Locate the message that contains the offset.
2779            while current_message.as_ref().map_or(false, |message| {
2780                !message.offset_range.contains(&offset) && messages.peek().is_some()
2781            }) {
2782                current_message = messages.next();
2783            }
2784            let Some(message) = current_message.as_ref() else {
2785                break;
2786            };
2787
2788            // Skip offsets that are in the same message.
2789            while offsets.peek().map_or(false, |offset| {
2790                message.offset_range.contains(offset) || messages.peek().is_none()
2791            }) {
2792                offsets.next();
2793            }
2794
2795            result.push(message.clone());
2796        }
2797        result
2798    }
2799
2800    fn messages_from_anchors<'a>(
2801        &'a self,
2802        message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2803        cx: &'a App,
2804    ) -> impl 'a + Iterator<Item = Message> {
2805        let buffer = self.buffer.read(cx);
2806
2807        Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2808    }
2809
2810    pub fn messages<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Message> {
2811        self.messages_from_anchors(self.message_anchors.iter(), cx)
2812    }
2813
2814    pub fn messages_from_iters<'a>(
2815        buffer: &'a Buffer,
2816        metadata: &'a HashMap<MessageId, MessageMetadata>,
2817        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2818    ) -> impl 'a + Iterator<Item = Message> {
2819        let mut messages = messages.peekable();
2820
2821        iter::from_fn(move || {
2822            if let Some((start_ix, message_anchor)) = messages.next() {
2823                let metadata = metadata.get(&message_anchor.id)?;
2824
2825                let message_start = message_anchor.start.to_offset(buffer);
2826                let mut message_end = None;
2827                let mut end_ix = start_ix;
2828                while let Some((_, next_message)) = messages.peek() {
2829                    if next_message.start.is_valid(buffer) {
2830                        message_end = Some(next_message.start);
2831                        break;
2832                    } else {
2833                        end_ix += 1;
2834                        messages.next();
2835                    }
2836                }
2837                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2838                let message_end = message_end_anchor.to_offset(buffer);
2839
2840                return Some(Message {
2841                    index_range: start_ix..end_ix,
2842                    offset_range: message_start..message_end,
2843                    anchor_range: message_anchor.start..message_end_anchor,
2844                    id: message_anchor.id,
2845                    role: metadata.role,
2846                    status: metadata.status.clone(),
2847                    cache: metadata.cache.clone(),
2848                });
2849            }
2850            None
2851        })
2852    }
2853
2854    pub fn save(
2855        &mut self,
2856        debounce: Option<Duration>,
2857        fs: Arc<dyn Fs>,
2858        cx: &mut Context<AssistantContext>,
2859    ) {
2860        if self.replica_id() != ReplicaId::default() {
2861            // Prevent saving a remote context for now.
2862            return;
2863        }
2864
2865        self.pending_save = cx.spawn(async move |this, cx| {
2866            if let Some(debounce) = debounce {
2867                cx.background_executor().timer(debounce).await;
2868            }
2869
2870            let (old_path, summary) = this.read_with(cx, |this, _| {
2871                let path = this.path.clone();
2872                let summary = if let Some(summary) = this.summary.content() {
2873                    if summary.done {
2874                        Some(summary.text.clone())
2875                    } else {
2876                        None
2877                    }
2878                } else {
2879                    None
2880                };
2881                (path, summary)
2882            })?;
2883
2884            if let Some(summary) = summary {
2885                let context = this.read_with(cx, |this, cx| this.serialize(cx))?;
2886                let mut discriminant = 1;
2887                let mut new_path;
2888                loop {
2889                    new_path = contexts_dir().join(&format!(
2890                        "{} - {}.zed.json",
2891                        summary.trim(),
2892                        discriminant
2893                    ));
2894                    if fs.is_file(&new_path).await {
2895                        discriminant += 1;
2896                    } else {
2897                        break;
2898                    }
2899                }
2900
2901                fs.create_dir(contexts_dir().as_ref()).await?;
2902
2903                // rename before write ensures that only one file exists
2904                if let Some(old_path) = old_path.as_ref() {
2905                    if new_path.as_path() != old_path.as_ref() {
2906                        fs.rename(
2907                            &old_path,
2908                            &new_path,
2909                            RenameOptions {
2910                                overwrite: true,
2911                                ignore_if_exists: true,
2912                            },
2913                        )
2914                        .await?;
2915                    }
2916                }
2917
2918                // update path before write in case it fails
2919                this.update(cx, {
2920                    let new_path: Arc<Path> = new_path.clone().into();
2921                    move |this, cx| {
2922                        this.path = Some(new_path.clone());
2923                        cx.emit(ContextEvent::PathChanged { old_path, new_path });
2924                    }
2925                })
2926                .ok();
2927
2928                fs.atomic_write(new_path, serde_json::to_string(&context).unwrap())
2929                    .await?;
2930            }
2931
2932            Ok(())
2933        });
2934    }
2935
2936    pub fn set_custom_summary(&mut self, custom_summary: String, cx: &mut Context<Self>) {
2937        let timestamp = self.next_timestamp();
2938        let summary = self.summary.content_or_set_empty();
2939        summary.timestamp = timestamp;
2940        summary.done = true;
2941        summary.text = custom_summary;
2942        cx.emit(ContextEvent::SummaryChanged);
2943    }
2944}
2945
2946#[derive(Debug, Default)]
2947pub struct ContextVersion {
2948    context: clock::Global,
2949    buffer: clock::Global,
2950}
2951
2952impl ContextVersion {
2953    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2954        Self {
2955            context: language::proto::deserialize_version(&proto.context_version),
2956            buffer: language::proto::deserialize_version(&proto.buffer_version),
2957        }
2958    }
2959
2960    pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
2961        proto::ContextVersion {
2962            context_id: context_id.to_proto(),
2963            context_version: language::proto::serialize_version(&self.context),
2964            buffer_version: language::proto::serialize_version(&self.buffer),
2965        }
2966    }
2967}
2968
2969#[derive(Debug, Clone)]
2970pub struct ParsedSlashCommand {
2971    pub name: String,
2972    pub arguments: SmallVec<[String; 3]>,
2973    pub status: PendingSlashCommandStatus,
2974    pub source_range: Range<language::Anchor>,
2975}
2976
2977#[derive(Debug)]
2978pub struct InvokedSlashCommand {
2979    pub name: SharedString,
2980    pub range: Range<language::Anchor>,
2981    pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
2982    pub status: InvokedSlashCommandStatus,
2983    pub transaction: Option<language::TransactionId>,
2984    timestamp: clock::Lamport,
2985}
2986
2987#[derive(Debug)]
2988pub enum InvokedSlashCommandStatus {
2989    Running(Task<()>),
2990    Error(SharedString),
2991    Finished,
2992}
2993
2994#[derive(Debug, Clone)]
2995pub enum PendingSlashCommandStatus {
2996    Idle,
2997    Running { _task: Shared<Task<()>> },
2998    Error(String),
2999}
3000
3001#[derive(Debug, Clone)]
3002pub struct PendingToolUse {
3003    pub id: LanguageModelToolUseId,
3004    pub name: String,
3005    pub input: serde_json::Value,
3006    pub status: PendingToolUseStatus,
3007    pub source_range: Range<language::Anchor>,
3008}
3009
3010#[derive(Debug, Clone)]
3011pub enum PendingToolUseStatus {
3012    Idle,
3013    Running { _task: Shared<Task<()>> },
3014    Error(String),
3015}
3016
3017impl PendingToolUseStatus {
3018    pub fn is_idle(&self) -> bool {
3019        matches!(self, PendingToolUseStatus::Idle)
3020    }
3021}
3022
3023#[derive(Serialize, Deserialize)]
3024pub struct SavedMessage {
3025    pub id: MessageId,
3026    pub start: usize,
3027    pub metadata: MessageMetadata,
3028}
3029
3030#[derive(Serialize, Deserialize)]
3031pub struct SavedContext {
3032    pub id: Option<ContextId>,
3033    pub zed: String,
3034    pub version: String,
3035    pub text: String,
3036    pub messages: Vec<SavedMessage>,
3037    pub summary: String,
3038    pub slash_command_output_sections:
3039        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3040    #[serde(default)]
3041    pub thought_process_output_sections: Vec<ThoughtProcessOutputSection<usize>>,
3042}
3043
3044impl SavedContext {
3045    pub const VERSION: &'static str = "0.4.0";
3046
3047    pub fn from_json(json: &str) -> Result<Self> {
3048        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3049        match saved_context_json
3050            .get("version")
3051            .context("version not found")?
3052        {
3053            serde_json::Value::String(version) => match version.as_str() {
3054                SavedContext::VERSION => {
3055                    Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
3056                }
3057                SavedContextV0_3_0::VERSION => {
3058                    let saved_context =
3059                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3060                    Ok(saved_context.upgrade())
3061                }
3062                SavedContextV0_2_0::VERSION => {
3063                    let saved_context =
3064                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3065                    Ok(saved_context.upgrade())
3066                }
3067                SavedContextV0_1_0::VERSION => {
3068                    let saved_context =
3069                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3070                    Ok(saved_context.upgrade())
3071                }
3072                _ => anyhow::bail!("unrecognized saved context version: {version:?}"),
3073            },
3074            _ => anyhow::bail!("version not found on saved context"),
3075        }
3076    }
3077
3078    fn into_ops(
3079        self,
3080        buffer: &Entity<Buffer>,
3081        cx: &mut Context<AssistantContext>,
3082    ) -> Vec<ContextOperation> {
3083        let mut operations = Vec::new();
3084        let mut version = clock::Global::new();
3085        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3086
3087        let mut first_message_metadata = None;
3088        for message in self.messages {
3089            if message.id == MessageId(clock::Lamport::default()) {
3090                first_message_metadata = Some(message.metadata);
3091            } else {
3092                operations.push(ContextOperation::InsertMessage {
3093                    anchor: MessageAnchor {
3094                        id: message.id,
3095                        start: buffer.read(cx).anchor_before(message.start),
3096                    },
3097                    metadata: MessageMetadata {
3098                        role: message.metadata.role,
3099                        status: message.metadata.status,
3100                        timestamp: message.metadata.timestamp,
3101                        cache: None,
3102                    },
3103                    version: version.clone(),
3104                });
3105                version.observe(message.id.0);
3106                next_timestamp.observe(message.id.0);
3107            }
3108        }
3109
3110        if let Some(metadata) = first_message_metadata {
3111            let timestamp = next_timestamp.tick();
3112            operations.push(ContextOperation::UpdateMessage {
3113                message_id: MessageId(clock::Lamport::default()),
3114                metadata: MessageMetadata {
3115                    role: metadata.role,
3116                    status: metadata.status,
3117                    timestamp,
3118                    cache: None,
3119                },
3120                version: version.clone(),
3121            });
3122            version.observe(timestamp);
3123        }
3124
3125        let buffer = buffer.read(cx);
3126        for section in self.slash_command_output_sections {
3127            let timestamp = next_timestamp.tick();
3128            operations.push(ContextOperation::SlashCommandOutputSectionAdded {
3129                timestamp,
3130                section: SlashCommandOutputSection {
3131                    range: buffer.anchor_after(section.range.start)
3132                        ..buffer.anchor_before(section.range.end),
3133                    icon: section.icon,
3134                    label: section.label,
3135                    metadata: section.metadata,
3136                },
3137                version: version.clone(),
3138            });
3139
3140            version.observe(timestamp);
3141        }
3142
3143        for section in self.thought_process_output_sections {
3144            let timestamp = next_timestamp.tick();
3145            operations.push(ContextOperation::ThoughtProcessOutputSectionAdded {
3146                timestamp,
3147                section: ThoughtProcessOutputSection {
3148                    range: buffer.anchor_after(section.range.start)
3149                        ..buffer.anchor_before(section.range.end),
3150                },
3151                version: version.clone(),
3152            });
3153
3154            version.observe(timestamp);
3155        }
3156
3157        let timestamp = next_timestamp.tick();
3158        operations.push(ContextOperation::UpdateSummary {
3159            summary: ContextSummaryContent {
3160                text: self.summary,
3161                done: true,
3162                timestamp,
3163            },
3164            version: version.clone(),
3165        });
3166        version.observe(timestamp);
3167
3168        operations
3169    }
3170}
3171
3172#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3173struct SavedMessageIdPreV0_4_0(usize);
3174
3175#[derive(Serialize, Deserialize)]
3176struct SavedMessagePreV0_4_0 {
3177    id: SavedMessageIdPreV0_4_0,
3178    start: usize,
3179}
3180
3181#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3182struct SavedMessageMetadataPreV0_4_0 {
3183    role: Role,
3184    status: MessageStatus,
3185}
3186
3187#[derive(Serialize, Deserialize)]
3188struct SavedContextV0_3_0 {
3189    id: Option<ContextId>,
3190    zed: String,
3191    version: String,
3192    text: String,
3193    messages: Vec<SavedMessagePreV0_4_0>,
3194    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3195    summary: String,
3196    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3197}
3198
3199impl SavedContextV0_3_0 {
3200    const VERSION: &'static str = "0.3.0";
3201
3202    fn upgrade(self) -> SavedContext {
3203        SavedContext {
3204            id: self.id,
3205            zed: self.zed,
3206            version: SavedContext::VERSION.into(),
3207            text: self.text,
3208            messages: self
3209                .messages
3210                .into_iter()
3211                .filter_map(|message| {
3212                    let metadata = self.message_metadata.get(&message.id)?;
3213                    let timestamp = clock::Lamport {
3214                        replica_id: ReplicaId::default(),
3215                        value: message.id.0 as u32,
3216                    };
3217                    Some(SavedMessage {
3218                        id: MessageId(timestamp),
3219                        start: message.start,
3220                        metadata: MessageMetadata {
3221                            role: metadata.role,
3222                            status: metadata.status.clone(),
3223                            timestamp,
3224                            cache: None,
3225                        },
3226                    })
3227                })
3228                .collect(),
3229            summary: self.summary,
3230            slash_command_output_sections: self.slash_command_output_sections,
3231            thought_process_output_sections: Vec::new(),
3232        }
3233    }
3234}
3235
3236#[derive(Serialize, Deserialize)]
3237struct SavedContextV0_2_0 {
3238    id: Option<ContextId>,
3239    zed: String,
3240    version: String,
3241    text: String,
3242    messages: Vec<SavedMessagePreV0_4_0>,
3243    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3244    summary: String,
3245}
3246
3247impl SavedContextV0_2_0 {
3248    const VERSION: &'static str = "0.2.0";
3249
3250    fn upgrade(self) -> SavedContext {
3251        SavedContextV0_3_0 {
3252            id: self.id,
3253            zed: self.zed,
3254            version: SavedContextV0_3_0::VERSION.to_string(),
3255            text: self.text,
3256            messages: self.messages,
3257            message_metadata: self.message_metadata,
3258            summary: self.summary,
3259            slash_command_output_sections: Vec::new(),
3260        }
3261        .upgrade()
3262    }
3263}
3264
3265#[derive(Serialize, Deserialize)]
3266struct SavedContextV0_1_0 {
3267    id: Option<ContextId>,
3268    zed: String,
3269    version: String,
3270    text: String,
3271    messages: Vec<SavedMessagePreV0_4_0>,
3272    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3273    summary: String,
3274    api_url: Option<String>,
3275    model: OpenAiModel,
3276}
3277
3278impl SavedContextV0_1_0 {
3279    const VERSION: &'static str = "0.1.0";
3280
3281    fn upgrade(self) -> SavedContext {
3282        SavedContextV0_2_0 {
3283            id: self.id,
3284            zed: self.zed,
3285            version: SavedContextV0_2_0::VERSION.to_string(),
3286            text: self.text,
3287            messages: self.messages,
3288            message_metadata: self.message_metadata,
3289            summary: self.summary,
3290        }
3291        .upgrade()
3292    }
3293}
3294
3295#[derive(Debug, Clone)]
3296pub struct SavedContextMetadata {
3297    pub title: SharedString,
3298    pub path: Arc<Path>,
3299    pub mtime: chrono::DateTime<chrono::Local>,
3300}