context.rs

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