text_thread.rs

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