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, UsageLimit};
  11use collections::{HashMap, HashSet};
  12use fs::{Fs, RenameOptions};
  13
  14use futures::{FutureExt, StreamExt, future::Shared};
  15use gpui::{
  16    App, AppContext as _, Context, Entity, EventEmitter, RenderImage, SharedString, Subscription,
  17    Task,
  18};
  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<usize>,
 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.contains_str_at(command_range_end, "\n")
1857                        {
1858                            let newline_offset = insert_position.saturating_sub(1);
1859                            if buffer.contains_str_at(newline_offset, "\n")
1860                                && last_section_range.is_none_or(|last_section_range| {
1861                                    !last_section_range
1862                                        .to_offset(buffer)
1863                                        .contains(&newline_offset)
1864                                })
1865                            {
1866                                deletions.push((command_range_end..command_range_end + 1, ""));
1867                            }
1868                        }
1869
1870                        buffer.edit(deletions, None, cx);
1871
1872                        if let Some(deletion_transaction) = buffer.end_transaction(cx) {
1873                            buffer.merge_transactions(deletion_transaction, first_transaction);
1874                        }
1875                    });
1876                })?;
1877
1878                debug_assert!(pending_section_stack.is_empty());
1879
1880                anyhow::Ok(())
1881            };
1882
1883            let command_result = run_command.await;
1884
1885            this.update(cx, |this, cx| {
1886                let version = this.version.clone();
1887                let timestamp = this.next_timestamp();
1888                let Some(invoked_slash_command) = this.invoked_slash_commands.get_mut(&command_id)
1889                else {
1890                    return;
1891                };
1892                let mut error_message = None;
1893                match command_result {
1894                    Ok(()) => {
1895                        invoked_slash_command.status = InvokedSlashCommandStatus::Finished;
1896                    }
1897                    Err(error) => {
1898                        let message = error.to_string();
1899                        invoked_slash_command.status =
1900                            InvokedSlashCommandStatus::Error(message.clone().into());
1901                        error_message = Some(message);
1902                    }
1903                }
1904
1905                cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1906                this.push_op(
1907                    TextThreadOperation::SlashCommandFinished {
1908                        id: command_id,
1909                        timestamp,
1910                        error_message,
1911                        version,
1912                    },
1913                    cx,
1914                );
1915            })
1916            .ok();
1917        });
1918
1919        self.invoked_slash_commands.insert(
1920            command_id,
1921            InvokedSlashCommand {
1922                name: name.to_string().into(),
1923                range: command_range.clone(),
1924                run_commands_in_ranges: Vec::new(),
1925                status: InvokedSlashCommandStatus::Running(insert_output_task),
1926                transaction: Some(first_transaction),
1927                timestamp: command_id.0,
1928            },
1929        );
1930        cx.emit(TextThreadEvent::InvokedSlashCommandChanged { command_id });
1931        self.push_op(
1932            TextThreadOperation::SlashCommandStarted {
1933                id: command_id,
1934                output_range: command_range,
1935                name: name.to_string(),
1936                version,
1937            },
1938            cx,
1939        );
1940    }
1941
1942    fn insert_slash_command_output_section(
1943        &mut self,
1944        section: SlashCommandOutputSection<language::Anchor>,
1945        cx: &mut Context<Self>,
1946    ) {
1947        let buffer = self.buffer.read(cx);
1948        let insertion_ix = match self
1949            .slash_command_output_sections
1950            .binary_search_by(|probe| probe.range.cmp(&section.range, buffer))
1951        {
1952            Ok(ix) | Err(ix) => ix,
1953        };
1954        self.slash_command_output_sections
1955            .insert(insertion_ix, section.clone());
1956        cx.emit(TextThreadEvent::SlashCommandOutputSectionAdded {
1957            section: section.clone(),
1958        });
1959        let version = self.version.clone();
1960        let timestamp = self.next_timestamp();
1961        self.push_op(
1962            TextThreadOperation::SlashCommandOutputSectionAdded {
1963                timestamp,
1964                section,
1965                version,
1966            },
1967            cx,
1968        );
1969    }
1970
1971    fn insert_thought_process_output_section(
1972        &mut self,
1973        section: ThoughtProcessOutputSection<language::Anchor>,
1974        cx: &mut Context<Self>,
1975    ) {
1976        let buffer = self.buffer.read(cx);
1977        let insertion_ix = match self
1978            .thought_process_output_sections
1979            .binary_search_by(|probe| probe.range.cmp(&section.range, buffer))
1980        {
1981            Ok(ix) | Err(ix) => ix,
1982        };
1983        self.thought_process_output_sections
1984            .insert(insertion_ix, section.clone());
1985        // cx.emit(ContextEvent::ThoughtProcessOutputSectionAdded {
1986        //     section: section.clone(),
1987        // });
1988        let version = self.version.clone();
1989        let timestamp = self.next_timestamp();
1990        self.push_op(
1991            TextThreadOperation::ThoughtProcessOutputSectionAdded {
1992                timestamp,
1993                section,
1994                version,
1995            },
1996            cx,
1997        );
1998    }
1999
2000    pub fn completion_provider_changed(&mut self, cx: &mut Context<Self>) {
2001        self.count_remaining_tokens(cx);
2002    }
2003
2004    fn get_last_valid_message_id(&self, cx: &Context<Self>) -> Option<MessageId> {
2005        self.message_anchors.iter().rev().find_map(|message| {
2006            message
2007                .start
2008                .is_valid(self.buffer.read(cx))
2009                .then_some(message.id)
2010        })
2011    }
2012
2013    pub fn assist(&mut self, cx: &mut Context<Self>) -> Option<MessageAnchor> {
2014        let model_registry = LanguageModelRegistry::read_global(cx);
2015        let model = model_registry.default_model()?;
2016        let last_message_id = self.get_last_valid_message_id(cx)?;
2017
2018        if !model.provider.is_authenticated(cx) {
2019            log::info!("completion provider has no credentials");
2020            return None;
2021        }
2022
2023        let model = model.model;
2024
2025        // Compute which messages to cache, including the last one.
2026        self.mark_cache_anchors(&model.cache_configuration(), false, cx);
2027
2028        let request = self.to_completion_request(Some(&model), cx);
2029
2030        let assistant_message = self
2031            .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
2032            .unwrap();
2033
2034        // Queue up the user's next reply.
2035        let user_message = self
2036            .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
2037            .unwrap();
2038
2039        let pending_completion_id = post_inc(&mut self.completion_count);
2040
2041        let task = cx.spawn({
2042            async move |this, cx| {
2043                let stream = model.stream_completion(request, cx);
2044                let assistant_message_id = assistant_message.id;
2045                let mut response_latency = None;
2046                let stream_completion = async {
2047                    let request_start = Instant::now();
2048                    let mut events = stream.await?;
2049                    let mut stop_reason = StopReason::EndTurn;
2050                    let mut thought_process_stack = Vec::new();
2051
2052                    const THOUGHT_PROCESS_START_MARKER: &str = "<think>\n";
2053                    const THOUGHT_PROCESS_END_MARKER: &str = "\n</think>";
2054
2055                    while let Some(event) = events.next().await {
2056                        if response_latency.is_none() {
2057                            response_latency = Some(request_start.elapsed());
2058                        }
2059                        let event = event?;
2060
2061                        let mut context_event = None;
2062                        let mut thought_process_output_section = None;
2063
2064                        this.update(cx, |this, cx| {
2065                            let message_ix = this
2066                                .message_anchors
2067                                .iter()
2068                                .position(|message| message.id == assistant_message_id)?;
2069                            this.buffer.update(cx, |buffer, cx| {
2070                                let message_old_end_offset = this.message_anchors[message_ix + 1..]
2071                                    .iter()
2072                                    .find(|message| message.start.is_valid(buffer))
2073                                    .map_or(buffer.len(), |message| {
2074                                        message.start.to_offset(buffer).saturating_sub(1)
2075                                    });
2076
2077                                match event {
2078                                    LanguageModelCompletionEvent::Started |
2079                                    LanguageModelCompletionEvent::Queued {..} |
2080                                    LanguageModelCompletionEvent::ToolUseLimitReached { .. } => {}
2081                                    LanguageModelCompletionEvent::UsageUpdated { amount, limit } => {
2082                                        this.update_model_request_usage(
2083                                            amount as u32,
2084                                            limit,
2085                                            cx,
2086                                        );
2087                                    }
2088                                    LanguageModelCompletionEvent::StartMessage { .. } => {}
2089                                    LanguageModelCompletionEvent::ReasoningDetails(_) => {
2090                                        // ReasoningDetails are metadata (signatures, encrypted data, format info)
2091                                        // used for request/response validation, not UI content.
2092                                        // The displayable thinking text is already handled by the Thinking event.
2093                                    }
2094                                    LanguageModelCompletionEvent::Stop(reason) => {
2095                                        stop_reason = reason;
2096                                    }
2097                                    LanguageModelCompletionEvent::Thinking { text: chunk, .. } => {
2098                                        if thought_process_stack.is_empty() {
2099                                            let start =
2100                                                buffer.anchor_before(message_old_end_offset);
2101                                            thought_process_stack.push(start);
2102                                            let chunk =
2103                                                format!("{THOUGHT_PROCESS_START_MARKER}{chunk}{THOUGHT_PROCESS_END_MARKER}");
2104                                            let chunk_len = chunk.len();
2105                                            buffer.edit(
2106                                                [(
2107                                                    message_old_end_offset..message_old_end_offset,
2108                                                    chunk,
2109                                                )],
2110                                                None,
2111                                                cx,
2112                                            );
2113                                            let end = buffer
2114                                                .anchor_before(message_old_end_offset + chunk_len);
2115                                            context_event = Some(
2116                                                TextThreadEvent::StartedThoughtProcess(start..end),
2117                                            );
2118                                        } else {
2119                                            // This ensures that all the thinking chunks are inserted inside the thinking tag
2120                                            let insertion_position =
2121                                                message_old_end_offset - THOUGHT_PROCESS_END_MARKER.len();
2122                                            buffer.edit(
2123                                                [(insertion_position..insertion_position, chunk)],
2124                                                None,
2125                                                cx,
2126                                            );
2127                                        }
2128                                    }
2129                                    LanguageModelCompletionEvent::RedactedThinking { .. } => {},
2130                                    LanguageModelCompletionEvent::Text(mut chunk) => {
2131                                        if let Some(start) = thought_process_stack.pop() {
2132                                            let end = buffer.anchor_before(message_old_end_offset);
2133                                            context_event =
2134                                                Some(TextThreadEvent::EndedThoughtProcess(end));
2135                                            thought_process_output_section =
2136                                                Some(ThoughtProcessOutputSection {
2137                                                    range: start..end,
2138                                                });
2139                                            chunk.insert_str(0, "\n\n");
2140                                        }
2141
2142                                        buffer.edit(
2143                                            [(
2144                                                message_old_end_offset..message_old_end_offset,
2145                                                chunk,
2146                                            )],
2147                                            None,
2148                                            cx,
2149                                        );
2150                                    }
2151                                    LanguageModelCompletionEvent::ToolUse(_) |
2152                                    LanguageModelCompletionEvent::ToolUseJsonParseError { .. } |
2153                                    LanguageModelCompletionEvent::UsageUpdate(_) => {}
2154                                }
2155                            });
2156
2157                            if let Some(section) = thought_process_output_section.take() {
2158                                this.insert_thought_process_output_section(section, cx);
2159                            }
2160                            if let Some(context_event) = context_event.take() {
2161                                cx.emit(context_event);
2162                            }
2163
2164                            cx.emit(TextThreadEvent::StreamedCompletion);
2165
2166                            Some(())
2167                        })?;
2168                        smol::future::yield_now().await;
2169                    }
2170                    this.update(cx, |this, cx| {
2171                        this.pending_completions
2172                            .retain(|completion| completion.id != pending_completion_id);
2173                        this.summarize(false, cx);
2174                        this.update_cache_status_for_completion(cx);
2175                    })?;
2176
2177                    anyhow::Ok(stop_reason)
2178                };
2179
2180                let result = stream_completion.await;
2181
2182                this.update(cx, |this, cx| {
2183                    let error_message = if let Some(error) = result.as_ref().err() {
2184                        if error.is::<PaymentRequiredError>() {
2185                            cx.emit(TextThreadEvent::ShowPaymentRequiredError);
2186                            this.update_metadata(assistant_message_id, cx, |metadata| {
2187                                metadata.status = MessageStatus::Canceled;
2188                            });
2189                            Some(error.to_string())
2190                        } else {
2191                            let error_message = error
2192                                .chain()
2193                                .map(|err| err.to_string())
2194                                .collect::<Vec<_>>()
2195                                .join("\n");
2196                            cx.emit(TextThreadEvent::ShowAssistError(SharedString::from(
2197                                error_message.clone(),
2198                            )));
2199                            this.update_metadata(assistant_message_id, cx, |metadata| {
2200                                metadata.status =
2201                                    MessageStatus::Error(SharedString::from(error_message.clone()));
2202                            });
2203                            Some(error_message)
2204                        }
2205                    } else {
2206                        this.update_metadata(assistant_message_id, cx, |metadata| {
2207                            metadata.status = MessageStatus::Done;
2208                        });
2209                        None
2210                    };
2211
2212                    let language_name = this
2213                        .buffer
2214                        .read(cx)
2215                        .language()
2216                        .map(|language| language.name());
2217                    report_assistant_event(
2218                        AssistantEventData {
2219                            conversation_id: Some(this.id.0.clone()),
2220                            kind: AssistantKind::Panel,
2221                            phase: AssistantPhase::Response,
2222                            message_id: None,
2223                            model: model.telemetry_id(),
2224                            model_provider: model.provider_id().to_string(),
2225                            response_latency,
2226                            error_message,
2227                            language_name: language_name.map(|name| name.to_proto()),
2228                        },
2229                        this.telemetry.clone(),
2230                        cx.http_client(),
2231                        model.api_key(cx),
2232                        cx.background_executor(),
2233                    );
2234
2235                    if let Ok(stop_reason) = result {
2236                        match stop_reason {
2237                            StopReason::ToolUse => {}
2238                            StopReason::EndTurn => {}
2239                            StopReason::MaxTokens => {}
2240                            StopReason::Refusal => {}
2241                        }
2242                    }
2243                })
2244                .ok();
2245            }
2246        });
2247
2248        self.pending_completions.push(PendingCompletion {
2249            id: pending_completion_id,
2250            assistant_message_id: assistant_message.id,
2251            _task: task,
2252        });
2253
2254        Some(user_message)
2255    }
2256
2257    pub fn to_xml(&self, cx: &App) -> String {
2258        let mut output = String::new();
2259        let buffer = self.buffer.read(cx);
2260        for message in self.messages(cx) {
2261            if message.status != MessageStatus::Done {
2262                continue;
2263            }
2264
2265            writeln!(&mut output, "<{}>", message.role).unwrap();
2266            for chunk in buffer.text_for_range(message.offset_range) {
2267                output.push_str(chunk);
2268            }
2269            if !output.ends_with('\n') {
2270                output.push('\n');
2271            }
2272            writeln!(&mut output, "</{}>", message.role).unwrap();
2273        }
2274        output
2275    }
2276
2277    pub fn to_completion_request(
2278        &self,
2279        model: Option<&Arc<dyn LanguageModel>>,
2280        cx: &App,
2281    ) -> LanguageModelRequest {
2282        let buffer = self.buffer.read(cx);
2283
2284        let mut contents = self.contents(cx).peekable();
2285
2286        fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2287            let text: String = buffer.text_for_range(range).collect();
2288            if text.trim().is_empty() {
2289                None
2290            } else {
2291                Some(text)
2292            }
2293        }
2294
2295        let mut completion_request = LanguageModelRequest {
2296            thread_id: None,
2297            prompt_id: None,
2298            intent: Some(CompletionIntent::UserPrompt),
2299            mode: None,
2300            messages: Vec::new(),
2301            tools: Vec::new(),
2302            tool_choice: None,
2303            stop: Vec::new(),
2304            temperature: model.and_then(|model| AgentSettings::temperature_for_model(model, cx)),
2305            thinking_allowed: true,
2306        };
2307        for message in self.messages(cx) {
2308            if message.status != MessageStatus::Done {
2309                continue;
2310            }
2311
2312            let mut offset = message.offset_range.start;
2313            let mut request_message = LanguageModelRequestMessage {
2314                role: message.role,
2315                content: Vec::new(),
2316                cache: message.cache.as_ref().is_some_and(|cache| cache.is_anchor),
2317                reasoning_details: None,
2318            };
2319
2320            while let Some(content) = contents.peek() {
2321                if content
2322                    .range()
2323                    .end
2324                    .cmp(&message.anchor_range.end, buffer)
2325                    .is_lt()
2326                {
2327                    let content = contents.next().unwrap();
2328                    let range = content.range().to_offset(buffer);
2329                    request_message.content.extend(
2330                        collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2331                    );
2332
2333                    match content {
2334                        Content::Image { image, .. } => {
2335                            if let Some(image) = image.clone().now_or_never().flatten() {
2336                                request_message
2337                                    .content
2338                                    .push(language_model::MessageContent::Image(image));
2339                            }
2340                        }
2341                    }
2342
2343                    offset = range.end;
2344                } else {
2345                    break;
2346                }
2347            }
2348
2349            request_message.content.extend(
2350                collect_text_content(buffer, offset..message.offset_range.end)
2351                    .map(MessageContent::Text),
2352            );
2353
2354            if !request_message.contents_empty() {
2355                completion_request.messages.push(request_message);
2356            }
2357        }
2358        let supports_burn_mode = if let Some(model) = model {
2359            model.supports_burn_mode()
2360        } else {
2361            false
2362        };
2363
2364        if supports_burn_mode {
2365            completion_request.mode = Some(self.completion_mode.into());
2366        }
2367        completion_request
2368    }
2369
2370    pub fn cancel_last_assist(&mut self, cx: &mut Context<Self>) -> bool {
2371        if let Some(pending_completion) = self.pending_completions.pop() {
2372            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2373                if metadata.status == MessageStatus::Pending {
2374                    metadata.status = MessageStatus::Canceled;
2375                }
2376            });
2377            true
2378        } else {
2379            false
2380        }
2381    }
2382
2383    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2384        for id in &ids {
2385            if let Some(metadata) = self.messages_metadata.get(id) {
2386                let role = metadata.role.cycle();
2387                self.update_metadata(*id, cx, |metadata| metadata.role = role);
2388            }
2389        }
2390
2391        self.message_roles_updated(ids, cx);
2392    }
2393
2394    fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut Context<Self>) {
2395        let mut ranges = Vec::new();
2396        for message in self.messages(cx) {
2397            if ids.contains(&message.id) {
2398                ranges.push(message.anchor_range.clone());
2399            }
2400        }
2401    }
2402
2403    pub fn update_metadata(
2404        &mut self,
2405        id: MessageId,
2406        cx: &mut Context<Self>,
2407        f: impl FnOnce(&mut MessageMetadata),
2408    ) {
2409        let version = self.version.clone();
2410        let timestamp = self.next_timestamp();
2411        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2412            f(metadata);
2413            metadata.timestamp = timestamp;
2414            let operation = TextThreadOperation::UpdateMessage {
2415                message_id: id,
2416                metadata: metadata.clone(),
2417                version,
2418            };
2419            self.push_op(operation, cx);
2420            cx.emit(TextThreadEvent::MessagesEdited);
2421            cx.notify();
2422        }
2423    }
2424
2425    pub fn insert_message_after(
2426        &mut self,
2427        message_id: MessageId,
2428        role: Role,
2429        status: MessageStatus,
2430        cx: &mut Context<Self>,
2431    ) -> Option<MessageAnchor> {
2432        if let Some(prev_message_ix) = self
2433            .message_anchors
2434            .iter()
2435            .position(|message| message.id == message_id)
2436        {
2437            // Find the next valid message after the one we were given.
2438            let mut next_message_ix = prev_message_ix + 1;
2439            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2440                if next_message.start.is_valid(self.buffer.read(cx)) {
2441                    break;
2442                }
2443                next_message_ix += 1;
2444            }
2445
2446            let buffer = self.buffer.read(cx);
2447            let offset = self
2448                .message_anchors
2449                .get(next_message_ix)
2450                .map_or(buffer.len(), |message| {
2451                    buffer.clip_offset(message.start.to_previous_offset(buffer), Bias::Left)
2452                });
2453            Some(self.insert_message_at_offset(offset, role, status, cx))
2454        } else {
2455            None
2456        }
2457    }
2458
2459    fn insert_message_at_offset(
2460        &mut self,
2461        offset: usize,
2462        role: Role,
2463        status: MessageStatus,
2464        cx: &mut Context<Self>,
2465    ) -> MessageAnchor {
2466        let start = self.buffer.update(cx, |buffer, cx| {
2467            buffer.edit([(offset..offset, "\n")], None, cx);
2468            buffer.anchor_before(offset + 1)
2469        });
2470
2471        let version = self.version.clone();
2472        let anchor = MessageAnchor {
2473            id: MessageId(self.next_timestamp()),
2474            start,
2475        };
2476        let metadata = MessageMetadata {
2477            role,
2478            status,
2479            timestamp: anchor.id.0,
2480            cache: None,
2481        };
2482        self.insert_message(anchor.clone(), metadata.clone(), cx);
2483        self.push_op(
2484            TextThreadOperation::InsertMessage {
2485                anchor: anchor.clone(),
2486                metadata,
2487                version,
2488            },
2489            cx,
2490        );
2491        anchor
2492    }
2493
2494    pub fn insert_content(&mut self, content: Content, cx: &mut Context<Self>) {
2495        let buffer = self.buffer.read(cx);
2496        let insertion_ix = match self
2497            .contents
2498            .binary_search_by(|probe| probe.cmp(&content, buffer))
2499        {
2500            Ok(ix) => {
2501                self.contents.remove(ix);
2502                ix
2503            }
2504            Err(ix) => ix,
2505        };
2506        self.contents.insert(insertion_ix, content);
2507        cx.emit(TextThreadEvent::MessagesEdited);
2508    }
2509
2510    pub fn contents<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Content> {
2511        let buffer = self.buffer.read(cx);
2512        self.contents
2513            .iter()
2514            .filter(|content| {
2515                let range = content.range();
2516                range.start.is_valid(buffer) && range.end.is_valid(buffer)
2517            })
2518            .cloned()
2519    }
2520
2521    pub fn split_message(
2522        &mut self,
2523        range: Range<usize>,
2524        cx: &mut Context<Self>,
2525    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2526        let start_message = self.message_for_offset(range.start, cx);
2527        let end_message = self.message_for_offset(range.end, cx);
2528        if let Some((start_message, end_message)) = start_message.zip(end_message) {
2529            // Prevent splitting when range spans multiple messages.
2530            if start_message.id != end_message.id {
2531                return (None, None);
2532            }
2533
2534            let message = start_message;
2535            let at_end = range.end >= message.offset_range.end.saturating_sub(1);
2536            let role_after = if range.start == range.end || at_end {
2537                Role::User
2538            } else {
2539                message.role
2540            };
2541            let role = message.role;
2542            let mut edited_buffer = false;
2543
2544            let mut suffix_start = None;
2545
2546            // TODO: why did this start panicking?
2547            if range.start > message.offset_range.start
2548                && range.end < message.offset_range.end.saturating_sub(1)
2549            {
2550                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2551                    suffix_start = Some(range.end + 1);
2552                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2553                    suffix_start = Some(range.end);
2554                }
2555            }
2556
2557            let version = self.version.clone();
2558            let suffix = if let Some(suffix_start) = suffix_start {
2559                MessageAnchor {
2560                    id: MessageId(self.next_timestamp()),
2561                    start: self.buffer.read(cx).anchor_before(suffix_start),
2562                }
2563            } else {
2564                self.buffer.update(cx, |buffer, cx| {
2565                    buffer.edit([(range.end..range.end, "\n")], None, cx);
2566                });
2567                edited_buffer = true;
2568                MessageAnchor {
2569                    id: MessageId(self.next_timestamp()),
2570                    start: self.buffer.read(cx).anchor_before(range.end + 1),
2571                }
2572            };
2573
2574            let suffix_metadata = MessageMetadata {
2575                role: role_after,
2576                status: MessageStatus::Done,
2577                timestamp: suffix.id.0,
2578                cache: None,
2579            };
2580            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2581            self.push_op(
2582                TextThreadOperation::InsertMessage {
2583                    anchor: suffix.clone(),
2584                    metadata: suffix_metadata,
2585                    version,
2586                },
2587                cx,
2588            );
2589
2590            let new_messages =
2591                if range.start == range.end || range.start == message.offset_range.start {
2592                    (None, Some(suffix))
2593                } else {
2594                    let mut prefix_end = None;
2595                    if range.start > message.offset_range.start
2596                        && range.end < message.offset_range.end - 1
2597                    {
2598                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2599                            prefix_end = Some(range.start + 1);
2600                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2601                            == Some('\n')
2602                        {
2603                            prefix_end = Some(range.start);
2604                        }
2605                    }
2606
2607                    let version = self.version.clone();
2608                    let selection = if let Some(prefix_end) = prefix_end {
2609                        MessageAnchor {
2610                            id: MessageId(self.next_timestamp()),
2611                            start: self.buffer.read(cx).anchor_before(prefix_end),
2612                        }
2613                    } else {
2614                        self.buffer.update(cx, |buffer, cx| {
2615                            buffer.edit([(range.start..range.start, "\n")], None, cx)
2616                        });
2617                        edited_buffer = true;
2618                        MessageAnchor {
2619                            id: MessageId(self.next_timestamp()),
2620                            start: self.buffer.read(cx).anchor_before(range.end + 1),
2621                        }
2622                    };
2623
2624                    let selection_metadata = MessageMetadata {
2625                        role,
2626                        status: MessageStatus::Done,
2627                        timestamp: selection.id.0,
2628                        cache: None,
2629                    };
2630                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2631                    self.push_op(
2632                        TextThreadOperation::InsertMessage {
2633                            anchor: selection.clone(),
2634                            metadata: selection_metadata,
2635                            version,
2636                        },
2637                        cx,
2638                    );
2639
2640                    (Some(selection), Some(suffix))
2641                };
2642
2643            if !edited_buffer {
2644                cx.emit(TextThreadEvent::MessagesEdited);
2645            }
2646            new_messages
2647        } else {
2648            (None, None)
2649        }
2650    }
2651
2652    fn insert_message(
2653        &mut self,
2654        new_anchor: MessageAnchor,
2655        new_metadata: MessageMetadata,
2656        cx: &mut Context<Self>,
2657    ) {
2658        cx.emit(TextThreadEvent::MessagesEdited);
2659
2660        self.messages_metadata.insert(new_anchor.id, new_metadata);
2661
2662        let buffer = self.buffer.read(cx);
2663        let insertion_ix = self
2664            .message_anchors
2665            .iter()
2666            .position(|anchor| {
2667                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2668                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2669            })
2670            .unwrap_or(self.message_anchors.len());
2671        self.message_anchors.insert(insertion_ix, new_anchor);
2672    }
2673
2674    pub fn summarize(&mut self, mut replace_old: bool, cx: &mut Context<Self>) {
2675        let Some(model) = LanguageModelRegistry::read_global(cx).thread_summary_model() else {
2676            return;
2677        };
2678
2679        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_pending()) {
2680            if !model.provider.is_authenticated(cx) {
2681                return;
2682            }
2683
2684            let mut request = self.to_completion_request(Some(&model.model), cx);
2685            request.messages.push(LanguageModelRequestMessage {
2686                role: Role::User,
2687                content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2688                cache: false,
2689                reasoning_details: None,
2690            });
2691
2692            // If there is no summary, it is set with `done: false` so that "Loading Summary…" can
2693            // be displayed.
2694            match self.summary {
2695                TextThreadSummary::Pending | TextThreadSummary::Error => {
2696                    self.summary = TextThreadSummary::Content(TextThreadSummaryContent {
2697                        text: "".to_string(),
2698                        done: false,
2699                        timestamp: clock::Lamport::MIN,
2700                    });
2701                    replace_old = true;
2702                }
2703                TextThreadSummary::Content(_) => {}
2704            }
2705
2706            self.summary_task = cx.spawn(async move |this, cx| {
2707                let result = async {
2708                    let stream = model.model.stream_completion_text(request, cx);
2709                    let mut messages = stream.await?;
2710
2711                    let mut replaced = !replace_old;
2712                    while let Some(message) = messages.stream.next().await {
2713                        let text = message?;
2714                        let mut lines = text.lines();
2715                        this.update(cx, |this, cx| {
2716                            let version = this.version.clone();
2717                            let timestamp = this.next_timestamp();
2718                            let summary = this.summary.content_or_set_empty();
2719                            if !replaced && replace_old {
2720                                summary.text.clear();
2721                                replaced = true;
2722                            }
2723                            summary.text.extend(lines.next());
2724                            summary.timestamp = timestamp;
2725                            let operation = TextThreadOperation::UpdateSummary {
2726                                summary: summary.clone(),
2727                                version,
2728                            };
2729                            this.push_op(operation, cx);
2730                            cx.emit(TextThreadEvent::SummaryChanged);
2731                            cx.emit(TextThreadEvent::SummaryGenerated);
2732                        })?;
2733
2734                        // Stop if the LLM generated multiple lines.
2735                        if lines.next().is_some() {
2736                            break;
2737                        }
2738                    }
2739
2740                    this.read_with(cx, |this, _cx| {
2741                        if let Some(summary) = this.summary.content()
2742                            && summary.text.is_empty()
2743                        {
2744                            bail!("Model generated an empty summary");
2745                        }
2746                        Ok(())
2747                    })??;
2748
2749                    this.update(cx, |this, cx| {
2750                        let version = this.version.clone();
2751                        let timestamp = this.next_timestamp();
2752                        if let Some(summary) = this.summary.content_as_mut() {
2753                            summary.done = true;
2754                            summary.timestamp = timestamp;
2755                            let operation = TextThreadOperation::UpdateSummary {
2756                                summary: summary.clone(),
2757                                version,
2758                            };
2759                            this.push_op(operation, cx);
2760                            cx.emit(TextThreadEvent::SummaryChanged);
2761                            cx.emit(TextThreadEvent::SummaryGenerated);
2762                        }
2763                    })?;
2764
2765                    anyhow::Ok(())
2766                }
2767                .await;
2768
2769                if let Err(err) = result {
2770                    this.update(cx, |this, cx| {
2771                        this.summary = TextThreadSummary::Error;
2772                        cx.emit(TextThreadEvent::SummaryChanged);
2773                    })
2774                    .log_err();
2775                    log::error!("Error generating context summary: {}", err);
2776                }
2777
2778                Some(())
2779            });
2780        }
2781    }
2782
2783    fn message_for_offset(&self, offset: usize, cx: &App) -> Option<Message> {
2784        self.messages_for_offsets([offset], cx).pop()
2785    }
2786
2787    pub fn messages_for_offsets(
2788        &self,
2789        offsets: impl IntoIterator<Item = usize>,
2790        cx: &App,
2791    ) -> Vec<Message> {
2792        let mut result = Vec::new();
2793
2794        let mut messages = self.messages(cx).peekable();
2795        let mut offsets = offsets.into_iter().peekable();
2796        let mut current_message = messages.next();
2797        while let Some(offset) = offsets.next() {
2798            // Locate the message that contains the offset.
2799            while current_message.as_ref().is_some_and(|message| {
2800                !message.offset_range.contains(&offset) && messages.peek().is_some()
2801            }) {
2802                current_message = messages.next();
2803            }
2804            let Some(message) = current_message.as_ref() else {
2805                break;
2806            };
2807
2808            // Skip offsets that are in the same message.
2809            while offsets.peek().is_some_and(|offset| {
2810                message.offset_range.contains(offset) || messages.peek().is_none()
2811            }) {
2812                offsets.next();
2813            }
2814
2815            result.push(message.clone());
2816        }
2817        result
2818    }
2819
2820    fn messages_from_anchors<'a>(
2821        &'a self,
2822        message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2823        cx: &'a App,
2824    ) -> impl 'a + Iterator<Item = Message> {
2825        let buffer = self.buffer.read(cx);
2826
2827        Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2828    }
2829
2830    pub fn messages<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = Message> {
2831        self.messages_from_anchors(self.message_anchors.iter(), cx)
2832    }
2833
2834    pub fn messages_from_iters<'a>(
2835        buffer: &'a Buffer,
2836        metadata: &'a HashMap<MessageId, MessageMetadata>,
2837        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2838    ) -> impl 'a + Iterator<Item = Message> {
2839        let mut messages = messages.peekable();
2840
2841        iter::from_fn(move || {
2842            if let Some((start_ix, message_anchor)) = messages.next() {
2843                let metadata = metadata.get(&message_anchor.id)?;
2844
2845                let message_start = message_anchor.start.to_offset(buffer);
2846                let mut message_end = None;
2847                let mut end_ix = start_ix;
2848                while let Some((_, next_message)) = messages.peek() {
2849                    if next_message.start.is_valid(buffer) {
2850                        message_end = Some(next_message.start);
2851                        break;
2852                    } else {
2853                        end_ix += 1;
2854                        messages.next();
2855                    }
2856                }
2857                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2858                let message_end = message_end_anchor.to_offset(buffer);
2859
2860                return Some(Message {
2861                    index_range: start_ix..end_ix,
2862                    offset_range: message_start..message_end,
2863                    anchor_range: message_anchor.start..message_end_anchor,
2864                    id: message_anchor.id,
2865                    role: metadata.role,
2866                    status: metadata.status.clone(),
2867                    cache: metadata.cache.clone(),
2868                });
2869            }
2870            None
2871        })
2872    }
2873
2874    pub fn save(
2875        &mut self,
2876        debounce: Option<Duration>,
2877        fs: Arc<dyn Fs>,
2878        cx: &mut Context<TextThread>,
2879    ) {
2880        if self.replica_id() != ReplicaId::default() {
2881            // Prevent saving a remote context for now.
2882            return;
2883        }
2884
2885        self.pending_save = cx.spawn(async move |this, cx| {
2886            if let Some(debounce) = debounce {
2887                cx.background_executor().timer(debounce).await;
2888            }
2889
2890            let (old_path, summary) = this.read_with(cx, |this, _| {
2891                let path = this.path.clone();
2892                let summary = if let Some(summary) = this.summary.content() {
2893                    if summary.done {
2894                        Some(summary.text.clone())
2895                    } else {
2896                        None
2897                    }
2898                } else {
2899                    None
2900                };
2901                (path, summary)
2902            })?;
2903
2904            if let Some(summary) = summary {
2905                let context = this.read_with(cx, |this, cx| this.serialize(cx))?;
2906                let mut discriminant = 1;
2907                let mut new_path;
2908                loop {
2909                    new_path = text_threads_dir().join(&format!(
2910                        "{} - {}.zed.json",
2911                        summary.trim(),
2912                        discriminant
2913                    ));
2914                    if fs.is_file(&new_path).await {
2915                        discriminant += 1;
2916                    } else {
2917                        break;
2918                    }
2919                }
2920
2921                fs.create_dir(text_threads_dir().as_ref()).await?;
2922
2923                // rename before write ensures that only one file exists
2924                if let Some(old_path) = old_path.as_ref()
2925                    && new_path.as_path() != old_path.as_ref()
2926                {
2927                    fs.rename(
2928                        old_path,
2929                        &new_path,
2930                        RenameOptions {
2931                            overwrite: true,
2932                            ignore_if_exists: true,
2933                        },
2934                    )
2935                    .await?;
2936                }
2937
2938                // update path before write in case it fails
2939                this.update(cx, {
2940                    let new_path: Arc<Path> = new_path.clone().into();
2941                    move |this, cx| {
2942                        this.path = Some(new_path.clone());
2943                        cx.emit(TextThreadEvent::PathChanged { old_path, new_path });
2944                    }
2945                })
2946                .ok();
2947
2948                fs.atomic_write(new_path, serde_json::to_string(&context).unwrap())
2949                    .await?;
2950            }
2951
2952            Ok(())
2953        });
2954    }
2955
2956    pub fn set_custom_summary(&mut self, custom_summary: String, cx: &mut Context<Self>) {
2957        let timestamp = self.next_timestamp();
2958        let summary = self.summary.content_or_set_empty();
2959        summary.timestamp = timestamp;
2960        summary.done = true;
2961        summary.text = custom_summary;
2962        cx.emit(TextThreadEvent::SummaryChanged);
2963    }
2964
2965    fn update_model_request_usage(&self, amount: u32, limit: UsageLimit, cx: &mut App) {
2966        let Some(project) = &self.project else {
2967            return;
2968        };
2969        project.read(cx).user_store().update(cx, |user_store, cx| {
2970            user_store.update_model_request_usage(
2971                ModelRequestUsage(RequestUsage {
2972                    amount: amount as i32,
2973                    limit,
2974                }),
2975                cx,
2976            )
2977        });
2978    }
2979}
2980
2981#[derive(Debug, Default)]
2982pub struct TextThreadVersion {
2983    text_thread: clock::Global,
2984    buffer: clock::Global,
2985}
2986
2987impl TextThreadVersion {
2988    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2989        Self {
2990            text_thread: language::proto::deserialize_version(&proto.context_version),
2991            buffer: language::proto::deserialize_version(&proto.buffer_version),
2992        }
2993    }
2994
2995    pub fn to_proto(&self, context_id: TextThreadId) -> proto::ContextVersion {
2996        proto::ContextVersion {
2997            context_id: context_id.to_proto(),
2998            context_version: language::proto::serialize_version(&self.text_thread),
2999            buffer_version: language::proto::serialize_version(&self.buffer),
3000        }
3001    }
3002}
3003
3004#[derive(Debug, Clone)]
3005pub struct ParsedSlashCommand {
3006    pub name: String,
3007    pub arguments: SmallVec<[String; 3]>,
3008    pub status: PendingSlashCommandStatus,
3009    pub source_range: Range<language::Anchor>,
3010}
3011
3012#[derive(Debug)]
3013pub struct InvokedSlashCommand {
3014    pub name: SharedString,
3015    pub range: Range<language::Anchor>,
3016    pub run_commands_in_ranges: Vec<Range<language::Anchor>>,
3017    pub status: InvokedSlashCommandStatus,
3018    pub transaction: Option<language::TransactionId>,
3019    timestamp: clock::Lamport,
3020}
3021
3022#[derive(Debug)]
3023pub enum InvokedSlashCommandStatus {
3024    Running(Task<()>),
3025    Error(SharedString),
3026    Finished,
3027}
3028
3029#[derive(Debug, Clone)]
3030pub enum PendingSlashCommandStatus {
3031    Idle,
3032    Running { _task: Shared<Task<()>> },
3033    Error(String),
3034}
3035
3036#[derive(Debug, Clone)]
3037pub struct PendingToolUse {
3038    pub id: LanguageModelToolUseId,
3039    pub name: String,
3040    pub input: serde_json::Value,
3041    pub status: PendingToolUseStatus,
3042    pub source_range: Range<language::Anchor>,
3043}
3044
3045#[derive(Debug, Clone)]
3046pub enum PendingToolUseStatus {
3047    Idle,
3048    Running { _task: Shared<Task<()>> },
3049    Error(String),
3050}
3051
3052impl PendingToolUseStatus {
3053    pub fn is_idle(&self) -> bool {
3054        matches!(self, PendingToolUseStatus::Idle)
3055    }
3056}
3057
3058#[derive(Serialize, Deserialize)]
3059pub struct SavedMessage {
3060    pub id: MessageId,
3061    pub start: usize,
3062    pub metadata: MessageMetadata,
3063}
3064
3065#[derive(Serialize, Deserialize)]
3066pub struct SavedTextThread {
3067    pub id: Option<TextThreadId>,
3068    pub zed: String,
3069    pub version: String,
3070    pub text: String,
3071    pub messages: Vec<SavedMessage>,
3072    pub summary: String,
3073    pub slash_command_output_sections:
3074        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3075    #[serde(default)]
3076    pub thought_process_output_sections: Vec<ThoughtProcessOutputSection<usize>>,
3077}
3078
3079impl SavedTextThread {
3080    pub const VERSION: &'static str = "0.4.0";
3081
3082    pub fn from_json(json: &str) -> Result<Self> {
3083        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
3084        match saved_context_json
3085            .get("version")
3086            .context("version not found")?
3087        {
3088            serde_json::Value::String(version) => match version.as_str() {
3089                SavedTextThread::VERSION => Ok(serde_json::from_value::<SavedTextThread>(
3090                    saved_context_json,
3091                )?),
3092                SavedContextV0_3_0::VERSION => {
3093                    let saved_context =
3094                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
3095                    Ok(saved_context.upgrade())
3096                }
3097                SavedContextV0_2_0::VERSION => {
3098                    let saved_context =
3099                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
3100                    Ok(saved_context.upgrade())
3101                }
3102                SavedContextV0_1_0::VERSION => {
3103                    let saved_context =
3104                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
3105                    Ok(saved_context.upgrade())
3106                }
3107                _ => anyhow::bail!("unrecognized saved context version: {version:?}"),
3108            },
3109            _ => anyhow::bail!("version not found on saved context"),
3110        }
3111    }
3112
3113    fn into_ops(
3114        self,
3115        buffer: &Entity<Buffer>,
3116        cx: &mut Context<TextThread>,
3117    ) -> Vec<TextThreadOperation> {
3118        let mut operations = Vec::new();
3119        let mut version = clock::Global::new();
3120        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
3121
3122        let mut first_message_metadata = None;
3123        for message in self.messages {
3124            if message.id == MessageId(clock::Lamport::MIN) {
3125                first_message_metadata = Some(message.metadata);
3126            } else {
3127                operations.push(TextThreadOperation::InsertMessage {
3128                    anchor: MessageAnchor {
3129                        id: message.id,
3130                        start: buffer.read(cx).anchor_before(message.start),
3131                    },
3132                    metadata: MessageMetadata {
3133                        role: message.metadata.role,
3134                        status: message.metadata.status,
3135                        timestamp: message.metadata.timestamp,
3136                        cache: None,
3137                    },
3138                    version: version.clone(),
3139                });
3140                version.observe(message.id.0);
3141                next_timestamp.observe(message.id.0);
3142            }
3143        }
3144
3145        if let Some(metadata) = first_message_metadata {
3146            let timestamp = next_timestamp.tick();
3147            operations.push(TextThreadOperation::UpdateMessage {
3148                message_id: MessageId(clock::Lamport::MIN),
3149                metadata: MessageMetadata {
3150                    role: metadata.role,
3151                    status: metadata.status,
3152                    timestamp,
3153                    cache: None,
3154                },
3155                version: version.clone(),
3156            });
3157            version.observe(timestamp);
3158        }
3159
3160        let buffer = buffer.read(cx);
3161        for section in self.slash_command_output_sections {
3162            let timestamp = next_timestamp.tick();
3163            operations.push(TextThreadOperation::SlashCommandOutputSectionAdded {
3164                timestamp,
3165                section: SlashCommandOutputSection {
3166                    range: buffer.anchor_after(section.range.start)
3167                        ..buffer.anchor_before(section.range.end),
3168                    icon: section.icon,
3169                    label: section.label,
3170                    metadata: section.metadata,
3171                },
3172                version: version.clone(),
3173            });
3174
3175            version.observe(timestamp);
3176        }
3177
3178        for section in self.thought_process_output_sections {
3179            let timestamp = next_timestamp.tick();
3180            operations.push(TextThreadOperation::ThoughtProcessOutputSectionAdded {
3181                timestamp,
3182                section: ThoughtProcessOutputSection {
3183                    range: buffer.anchor_after(section.range.start)
3184                        ..buffer.anchor_before(section.range.end),
3185                },
3186                version: version.clone(),
3187            });
3188
3189            version.observe(timestamp);
3190        }
3191
3192        let timestamp = next_timestamp.tick();
3193        operations.push(TextThreadOperation::UpdateSummary {
3194            summary: TextThreadSummaryContent {
3195                text: self.summary,
3196                done: true,
3197                timestamp,
3198            },
3199            version: version.clone(),
3200        });
3201        version.observe(timestamp);
3202
3203        operations
3204    }
3205}
3206
3207#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3208struct SavedMessageIdPreV0_4_0(usize);
3209
3210#[derive(Serialize, Deserialize)]
3211struct SavedMessagePreV0_4_0 {
3212    id: SavedMessageIdPreV0_4_0,
3213    start: usize,
3214}
3215
3216#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3217struct SavedMessageMetadataPreV0_4_0 {
3218    role: Role,
3219    status: MessageStatus,
3220}
3221
3222#[derive(Serialize, Deserialize)]
3223struct SavedContextV0_3_0 {
3224    id: Option<TextThreadId>,
3225    zed: String,
3226    version: String,
3227    text: String,
3228    messages: Vec<SavedMessagePreV0_4_0>,
3229    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3230    summary: String,
3231    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3232}
3233
3234impl SavedContextV0_3_0 {
3235    const VERSION: &'static str = "0.3.0";
3236
3237    fn upgrade(self) -> SavedTextThread {
3238        SavedTextThread {
3239            id: self.id,
3240            zed: self.zed,
3241            version: SavedTextThread::VERSION.into(),
3242            text: self.text,
3243            messages: self
3244                .messages
3245                .into_iter()
3246                .filter_map(|message| {
3247                    let metadata = self.message_metadata.get(&message.id)?;
3248                    let timestamp = clock::Lamport {
3249                        replica_id: ReplicaId::default(),
3250                        value: message.id.0 as u32,
3251                    };
3252                    Some(SavedMessage {
3253                        id: MessageId(timestamp),
3254                        start: message.start,
3255                        metadata: MessageMetadata {
3256                            role: metadata.role,
3257                            status: metadata.status.clone(),
3258                            timestamp,
3259                            cache: None,
3260                        },
3261                    })
3262                })
3263                .collect(),
3264            summary: self.summary,
3265            slash_command_output_sections: self.slash_command_output_sections,
3266            thought_process_output_sections: Vec::new(),
3267        }
3268    }
3269}
3270
3271#[derive(Serialize, Deserialize)]
3272struct SavedContextV0_2_0 {
3273    id: Option<TextThreadId>,
3274    zed: String,
3275    version: String,
3276    text: String,
3277    messages: Vec<SavedMessagePreV0_4_0>,
3278    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3279    summary: String,
3280}
3281
3282impl SavedContextV0_2_0 {
3283    const VERSION: &'static str = "0.2.0";
3284
3285    fn upgrade(self) -> SavedTextThread {
3286        SavedContextV0_3_0 {
3287            id: self.id,
3288            zed: self.zed,
3289            version: SavedContextV0_3_0::VERSION.to_string(),
3290            text: self.text,
3291            messages: self.messages,
3292            message_metadata: self.message_metadata,
3293            summary: self.summary,
3294            slash_command_output_sections: Vec::new(),
3295        }
3296        .upgrade()
3297    }
3298}
3299
3300#[derive(Serialize, Deserialize)]
3301struct SavedContextV0_1_0 {
3302    id: Option<TextThreadId>,
3303    zed: String,
3304    version: String,
3305    text: String,
3306    messages: Vec<SavedMessagePreV0_4_0>,
3307    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3308    summary: String,
3309    api_url: Option<String>,
3310    model: OpenAiModel,
3311}
3312
3313impl SavedContextV0_1_0 {
3314    const VERSION: &'static str = "0.1.0";
3315
3316    fn upgrade(self) -> SavedTextThread {
3317        SavedContextV0_2_0 {
3318            id: self.id,
3319            zed: self.zed,
3320            version: SavedContextV0_2_0::VERSION.to_string(),
3321            text: self.text,
3322            messages: self.messages,
3323            message_metadata: self.message_metadata,
3324            summary: self.summary,
3325        }
3326        .upgrade()
3327    }
3328}
3329
3330#[derive(Debug, Clone)]
3331pub struct SavedTextThreadMetadata {
3332    pub title: SharedString,
3333    pub path: Arc<Path>,
3334    pub mtime: chrono::DateTime<chrono::Local>,
3335}