text_thread.rs

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