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