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);
 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    ) {
 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
 772    fn flush_ops(&mut self, cx: &mut ModelContext<Context>) {
 773        let mut changed_messages = HashSet::default();
 774        let mut summary_changed = false;
 775
 776        self.pending_ops.sort_unstable_by_key(|op| op.timestamp());
 777        for op in mem::take(&mut self.pending_ops) {
 778            if !self.can_apply_op(&op, cx) {
 779                self.pending_ops.push(op);
 780                continue;
 781            }
 782
 783            let timestamp = op.timestamp();
 784            match op.clone() {
 785                ContextOperation::InsertMessage {
 786                    anchor, metadata, ..
 787                } => {
 788                    if self.messages_metadata.contains_key(&anchor.id) {
 789                        // We already applied this operation.
 790                    } else {
 791                        changed_messages.insert(anchor.id);
 792                        self.insert_message(anchor, metadata, cx);
 793                    }
 794                }
 795                ContextOperation::UpdateMessage {
 796                    message_id,
 797                    metadata: new_metadata,
 798                    ..
 799                } => {
 800                    let metadata = self.messages_metadata.get_mut(&message_id).unwrap();
 801                    if new_metadata.timestamp > metadata.timestamp {
 802                        *metadata = new_metadata;
 803                        changed_messages.insert(message_id);
 804                    }
 805                }
 806                ContextOperation::UpdateSummary {
 807                    summary: new_summary,
 808                    ..
 809                } => {
 810                    if self
 811                        .summary
 812                        .as_ref()
 813                        .map_or(true, |summary| new_summary.timestamp > summary.timestamp)
 814                    {
 815                        self.summary = Some(new_summary);
 816                        summary_changed = true;
 817                    }
 818                }
 819                ContextOperation::SlashCommandFinished {
 820                    id,
 821                    output_range,
 822                    sections,
 823                    ..
 824                } => {
 825                    if self.finished_slash_commands.insert(id) {
 826                        let buffer = self.buffer.read(cx);
 827                        self.slash_command_output_sections
 828                            .extend(sections.iter().cloned());
 829                        self.slash_command_output_sections
 830                            .sort_by(|a, b| a.range.cmp(&b.range, buffer));
 831                        cx.emit(ContextEvent::SlashCommandFinished {
 832                            output_range,
 833                            sections,
 834                            expand_result: false,
 835                            run_commands_in_output: false,
 836                        });
 837                    }
 838                }
 839                ContextOperation::BufferOperation(_) => unreachable!(),
 840            }
 841
 842            self.version.observe(timestamp);
 843            self.timestamp.observe(timestamp);
 844            self.operations.push(op);
 845        }
 846
 847        if !changed_messages.is_empty() {
 848            self.message_roles_updated(changed_messages, cx);
 849            cx.emit(ContextEvent::MessagesEdited);
 850            cx.notify();
 851        }
 852
 853        if summary_changed {
 854            cx.emit(ContextEvent::SummaryChanged);
 855            cx.notify();
 856        }
 857    }
 858
 859    fn can_apply_op(&self, op: &ContextOperation, cx: &AppContext) -> bool {
 860        if !self.version.observed_all(op.version()) {
 861            return false;
 862        }
 863
 864        match op {
 865            ContextOperation::InsertMessage { anchor, .. } => self
 866                .buffer
 867                .read(cx)
 868                .version
 869                .observed(anchor.start.timestamp),
 870            ContextOperation::UpdateMessage { message_id, .. } => {
 871                self.messages_metadata.contains_key(message_id)
 872            }
 873            ContextOperation::UpdateSummary { .. } => true,
 874            ContextOperation::SlashCommandFinished {
 875                output_range,
 876                sections,
 877                ..
 878            } => {
 879                let version = &self.buffer.read(cx).version;
 880                sections
 881                    .iter()
 882                    .map(|section| &section.range)
 883                    .chain([output_range])
 884                    .all(|range| {
 885                        let observed_start = range.start == language::Anchor::MIN
 886                            || range.start == language::Anchor::MAX
 887                            || version.observed(range.start.timestamp);
 888                        let observed_end = range.end == language::Anchor::MIN
 889                            || range.end == language::Anchor::MAX
 890                            || version.observed(range.end.timestamp);
 891                        observed_start && observed_end
 892                    })
 893            }
 894            ContextOperation::BufferOperation(_) => {
 895                panic!("buffer operations should always be applied")
 896            }
 897        }
 898    }
 899
 900    fn push_op(&mut self, op: ContextOperation, cx: &mut ModelContext<Self>) {
 901        self.operations.push(op.clone());
 902        cx.emit(ContextEvent::Operation(op));
 903    }
 904
 905    pub fn buffer(&self) -> &Model<Buffer> {
 906        &self.buffer
 907    }
 908
 909    pub fn language_registry(&self) -> Arc<LanguageRegistry> {
 910        self.language_registry.clone()
 911    }
 912
 913    pub fn project(&self) -> Option<Model<Project>> {
 914        self.project.clone()
 915    }
 916
 917    pub fn prompt_builder(&self) -> Arc<PromptBuilder> {
 918        self.prompt_builder.clone()
 919    }
 920
 921    pub fn path(&self) -> Option<&Path> {
 922        self.path.as_deref()
 923    }
 924
 925    pub fn summary(&self) -> Option<&ContextSummary> {
 926        self.summary.as_ref()
 927    }
 928
 929    pub(crate) fn workflow_step_containing(
 930        &self,
 931        offset: usize,
 932        cx: &AppContext,
 933    ) -> Option<&WorkflowStep> {
 934        let buffer = self.buffer.read(cx);
 935        let index = self
 936            .workflow_steps
 937            .binary_search_by(|step| {
 938                let step_range = step.range.to_offset(&buffer);
 939                if offset < step_range.start {
 940                    Ordering::Greater
 941                } else if offset > step_range.end {
 942                    Ordering::Less
 943                } else {
 944                    Ordering::Equal
 945                }
 946            })
 947            .ok()?;
 948        Some(&self.workflow_steps[index])
 949    }
 950
 951    pub fn workflow_step_ranges(&self) -> impl Iterator<Item = Range<language::Anchor>> + '_ {
 952        self.workflow_steps.iter().map(|step| step.range.clone())
 953    }
 954
 955    pub(crate) fn workflow_step_for_range(
 956        &self,
 957        range: &Range<language::Anchor>,
 958        cx: &AppContext,
 959    ) -> Option<&WorkflowStep> {
 960        let buffer = self.buffer.read(cx);
 961        let index = self.workflow_step_index_for_range(range, buffer).ok()?;
 962        Some(&self.workflow_steps[index])
 963    }
 964
 965    fn workflow_step_index_for_range(
 966        &self,
 967        tagged_range: &Range<text::Anchor>,
 968        buffer: &text::BufferSnapshot,
 969    ) -> Result<usize, usize> {
 970        self.workflow_steps
 971            .binary_search_by(|probe| probe.range.cmp(&tagged_range, buffer))
 972    }
 973
 974    pub fn pending_slash_commands(&self) -> &[PendingSlashCommand] {
 975        &self.pending_slash_commands
 976    }
 977
 978    pub fn slash_command_output_sections(&self) -> &[SlashCommandOutputSection<language::Anchor>] {
 979        &self.slash_command_output_sections
 980    }
 981
 982    pub fn pending_tool_uses(&self) -> Vec<&PendingToolUse> {
 983        self.pending_tool_uses_by_id.values().collect()
 984    }
 985
 986    pub fn get_tool_use_by_id(&self, id: &Arc<str>) -> Option<&PendingToolUse> {
 987        self.pending_tool_uses_by_id.get(id)
 988    }
 989
 990    fn set_language(&mut self, cx: &mut ModelContext<Self>) {
 991        let markdown = self.language_registry.language_for_name("Markdown");
 992        cx.spawn(|this, mut cx| async move {
 993            let markdown = markdown.await?;
 994            this.update(&mut cx, |this, cx| {
 995                this.buffer
 996                    .update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx));
 997            })
 998        })
 999        .detach_and_log_err(cx);
1000    }
1001
1002    fn handle_buffer_event(
1003        &mut self,
1004        _: Model<Buffer>,
1005        event: &language::BufferEvent,
1006        cx: &mut ModelContext<Self>,
1007    ) {
1008        match event {
1009            language::BufferEvent::Operation(operation) => cx.emit(ContextEvent::Operation(
1010                ContextOperation::BufferOperation(operation.clone()),
1011            )),
1012            language::BufferEvent::Edited => {
1013                self.count_remaining_tokens(cx);
1014                self.reparse(cx);
1015                // Use `inclusive = true` to invalidate a step when an edit occurs
1016                // at the start/end of a parsed step.
1017                cx.emit(ContextEvent::MessagesEdited);
1018            }
1019            _ => {}
1020        }
1021    }
1022
1023    pub(crate) fn token_count(&self) -> Option<usize> {
1024        self.token_count
1025    }
1026
1027    pub(crate) fn count_remaining_tokens(&mut self, cx: &mut ModelContext<Self>) {
1028        let request = self.to_completion_request(cx);
1029        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1030            return;
1031        };
1032        self.pending_token_count = cx.spawn(|this, mut cx| {
1033            async move {
1034                cx.background_executor()
1035                    .timer(Duration::from_millis(200))
1036                    .await;
1037
1038                let token_count = cx.update(|cx| model.count_tokens(request, cx))?.await?;
1039                this.update(&mut cx, |this, cx| {
1040                    this.token_count = Some(token_count);
1041                    this.start_cache_warming(&model, cx);
1042                    cx.notify()
1043                })
1044            }
1045            .log_err()
1046        });
1047    }
1048
1049    pub fn mark_cache_anchors(
1050        &mut self,
1051        cache_configuration: &Option<LanguageModelCacheConfiguration>,
1052        speculative: bool,
1053        cx: &mut ModelContext<Self>,
1054    ) -> bool {
1055        let cache_configuration =
1056            cache_configuration
1057                .as_ref()
1058                .unwrap_or(&LanguageModelCacheConfiguration {
1059                    max_cache_anchors: 0,
1060                    should_speculate: false,
1061                    min_total_token: 0,
1062                });
1063
1064        let messages: Vec<Message> = self.messages(cx).collect();
1065
1066        let mut sorted_messages = messages.clone();
1067        if speculative {
1068            // Avoid caching the last message if this is a speculative cache fetch as
1069            // it's likely to change.
1070            sorted_messages.pop();
1071        }
1072        sorted_messages.retain(|m| m.role == Role::User);
1073        sorted_messages.sort_by(|a, b| b.offset_range.len().cmp(&a.offset_range.len()));
1074
1075        let cache_anchors = if self.token_count.unwrap_or(0) < cache_configuration.min_total_token {
1076            // If we have't hit the minimum threshold to enable caching, don't cache anything.
1077            0
1078        } else {
1079            // Save 1 anchor for the inline assistant to use.
1080            max(cache_configuration.max_cache_anchors, 1) - 1
1081        };
1082        sorted_messages.truncate(cache_anchors);
1083
1084        let anchors: HashSet<MessageId> = sorted_messages
1085            .into_iter()
1086            .map(|message| message.id)
1087            .collect();
1088
1089        let buffer = self.buffer.read(cx).snapshot();
1090        let invalidated_caches: HashSet<MessageId> = messages
1091            .iter()
1092            .scan(false, |encountered_invalid, message| {
1093                let message_id = message.id;
1094                let is_invalid = self
1095                    .messages_metadata
1096                    .get(&message_id)
1097                    .map_or(true, |metadata| {
1098                        !metadata.is_cache_valid(&buffer, &message.offset_range)
1099                            || *encountered_invalid
1100                    });
1101                *encountered_invalid |= is_invalid;
1102                Some(if is_invalid { Some(message_id) } else { None })
1103            })
1104            .flatten()
1105            .collect();
1106
1107        let last_anchor = messages.iter().rev().find_map(|message| {
1108            if anchors.contains(&message.id) {
1109                Some(message.id)
1110            } else {
1111                None
1112            }
1113        });
1114
1115        let mut new_anchor_needs_caching = false;
1116        let current_version = &buffer.version;
1117        // If we have no anchors, mark all messages as not being cached.
1118        let mut hit_last_anchor = last_anchor.is_none();
1119
1120        for message in messages.iter() {
1121            if hit_last_anchor {
1122                self.update_metadata(message.id, cx, |metadata| metadata.cache = None);
1123                continue;
1124            }
1125
1126            if let Some(last_anchor) = last_anchor {
1127                if message.id == last_anchor {
1128                    hit_last_anchor = true;
1129                }
1130            }
1131
1132            new_anchor_needs_caching = new_anchor_needs_caching
1133                || (invalidated_caches.contains(&message.id) && anchors.contains(&message.id));
1134
1135            self.update_metadata(message.id, cx, |metadata| {
1136                let cache_status = if invalidated_caches.contains(&message.id) {
1137                    CacheStatus::Pending
1138                } else {
1139                    metadata
1140                        .cache
1141                        .as_ref()
1142                        .map_or(CacheStatus::Pending, |cm| cm.status.clone())
1143                };
1144                metadata.cache = Some(MessageCacheMetadata {
1145                    is_anchor: anchors.contains(&message.id),
1146                    is_final_anchor: hit_last_anchor,
1147                    status: cache_status,
1148                    cached_at: current_version.clone(),
1149                });
1150            });
1151        }
1152        new_anchor_needs_caching
1153    }
1154
1155    fn start_cache_warming(&mut self, model: &Arc<dyn LanguageModel>, cx: &mut ModelContext<Self>) {
1156        let cache_configuration = model.cache_configuration();
1157
1158        if !self.mark_cache_anchors(&cache_configuration, true, cx) {
1159            return;
1160        }
1161        if !self.pending_completions.is_empty() {
1162            return;
1163        }
1164        if let Some(cache_configuration) = cache_configuration {
1165            if !cache_configuration.should_speculate {
1166                return;
1167            }
1168        }
1169
1170        let request = {
1171            let mut req = self.to_completion_request(cx);
1172            // Skip the last message because it's likely to change and
1173            // therefore would be a waste to cache.
1174            req.messages.pop();
1175            req.messages.push(LanguageModelRequestMessage {
1176                role: Role::User,
1177                content: vec!["Respond only with OK, nothing else.".into()],
1178                cache: false,
1179            });
1180            req
1181        };
1182
1183        let model = Arc::clone(model);
1184        self.pending_cache_warming_task = cx.spawn(|this, mut cx| {
1185            async move {
1186                match model.stream_completion(request, &cx).await {
1187                    Ok(mut stream) => {
1188                        stream.next().await;
1189                        log::info!("Cache warming completed successfully");
1190                    }
1191                    Err(e) => {
1192                        log::warn!("Cache warming failed: {}", e);
1193                    }
1194                };
1195                this.update(&mut cx, |this, cx| {
1196                    this.update_cache_status_for_completion(cx);
1197                })
1198                .ok();
1199                anyhow::Ok(())
1200            }
1201            .log_err()
1202        });
1203    }
1204
1205    pub fn update_cache_status_for_completion(&mut self, cx: &mut ModelContext<Self>) {
1206        let cached_message_ids: Vec<MessageId> = self
1207            .messages_metadata
1208            .iter()
1209            .filter_map(|(message_id, metadata)| {
1210                metadata.cache.as_ref().and_then(|cache| {
1211                    if cache.status == CacheStatus::Pending {
1212                        Some(*message_id)
1213                    } else {
1214                        None
1215                    }
1216                })
1217            })
1218            .collect();
1219
1220        for message_id in cached_message_ids {
1221            self.update_metadata(message_id, cx, |metadata| {
1222                if let Some(cache) = &mut metadata.cache {
1223                    cache.status = CacheStatus::Cached;
1224                }
1225            });
1226        }
1227        cx.notify();
1228    }
1229
1230    pub fn reparse(&mut self, cx: &mut ModelContext<Self>) {
1231        let buffer = self.buffer.read(cx).text_snapshot();
1232        let mut row_ranges = self
1233            .edits_since_last_parse
1234            .consume()
1235            .into_iter()
1236            .map(|edit| {
1237                let start_row = buffer.offset_to_point(edit.new.start).row;
1238                let end_row = buffer.offset_to_point(edit.new.end).row + 1;
1239                start_row..end_row
1240            })
1241            .peekable();
1242
1243        let mut removed_slash_command_ranges = Vec::new();
1244        let mut updated_slash_commands = Vec::new();
1245        let mut removed_steps = Vec::new();
1246        let mut updated_steps = Vec::new();
1247        while let Some(mut row_range) = row_ranges.next() {
1248            while let Some(next_row_range) = row_ranges.peek() {
1249                if row_range.end >= next_row_range.start {
1250                    row_range.end = next_row_range.end;
1251                    row_ranges.next();
1252                } else {
1253                    break;
1254                }
1255            }
1256
1257            let start = buffer.anchor_before(Point::new(row_range.start, 0));
1258            let end = buffer.anchor_after(Point::new(
1259                row_range.end - 1,
1260                buffer.line_len(row_range.end - 1),
1261            ));
1262
1263            self.reparse_slash_commands_in_range(
1264                start..end,
1265                &buffer,
1266                &mut updated_slash_commands,
1267                &mut removed_slash_command_ranges,
1268                cx,
1269            );
1270            self.reparse_workflow_steps_in_range(
1271                start..end,
1272                &buffer,
1273                &mut updated_steps,
1274                &mut removed_steps,
1275                cx,
1276            );
1277        }
1278
1279        if !updated_slash_commands.is_empty() || !removed_slash_command_ranges.is_empty() {
1280            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1281                removed: removed_slash_command_ranges,
1282                updated: updated_slash_commands,
1283            });
1284        }
1285
1286        if !updated_steps.is_empty() || !removed_steps.is_empty() {
1287            cx.emit(ContextEvent::WorkflowStepsUpdated {
1288                removed: removed_steps,
1289                updated: updated_steps,
1290            });
1291        }
1292    }
1293
1294    fn reparse_slash_commands_in_range(
1295        &mut self,
1296        range: Range<text::Anchor>,
1297        buffer: &BufferSnapshot,
1298        updated: &mut Vec<PendingSlashCommand>,
1299        removed: &mut Vec<Range<text::Anchor>>,
1300        cx: &AppContext,
1301    ) {
1302        let old_range = self.pending_command_indices_for_range(range.clone(), cx);
1303
1304        let mut new_commands = Vec::new();
1305        let mut lines = buffer.text_for_range(range).lines();
1306        let mut offset = lines.offset();
1307        while let Some(line) = lines.next() {
1308            if let Some(command_line) = SlashCommandLine::parse(line) {
1309                let name = &line[command_line.name.clone()];
1310                let arguments = command_line
1311                    .arguments
1312                    .iter()
1313                    .filter_map(|argument_range| {
1314                        if argument_range.is_empty() {
1315                            None
1316                        } else {
1317                            line.get(argument_range.clone())
1318                        }
1319                    })
1320                    .map(ToOwned::to_owned)
1321                    .collect::<SmallVec<_>>();
1322                if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1323                    if !command.requires_argument() || !arguments.is_empty() {
1324                        let start_ix = offset + command_line.name.start - 1;
1325                        let end_ix = offset
1326                            + command_line
1327                                .arguments
1328                                .last()
1329                                .map_or(command_line.name.end, |argument| argument.end);
1330                        let source_range =
1331                            buffer.anchor_after(start_ix)..buffer.anchor_after(end_ix);
1332                        let pending_command = PendingSlashCommand {
1333                            name: name.to_string(),
1334                            arguments,
1335                            source_range,
1336                            status: PendingSlashCommandStatus::Idle,
1337                        };
1338                        updated.push(pending_command.clone());
1339                        new_commands.push(pending_command);
1340                    }
1341                }
1342            }
1343
1344            offset = lines.offset();
1345        }
1346
1347        let removed_commands = self.pending_slash_commands.splice(old_range, new_commands);
1348        removed.extend(removed_commands.map(|command| command.source_range));
1349    }
1350
1351    fn reparse_workflow_steps_in_range(
1352        &mut self,
1353        range: Range<text::Anchor>,
1354        buffer: &BufferSnapshot,
1355        updated: &mut Vec<Range<text::Anchor>>,
1356        removed: &mut Vec<Range<text::Anchor>>,
1357        cx: &mut ModelContext<Self>,
1358    ) {
1359        // Rebuild the XML tags in the edited range.
1360        let intersecting_tags_range =
1361            self.indices_intersecting_buffer_range(&self.xml_tags, range.clone(), cx);
1362        let new_tags = self.parse_xml_tags_in_range(buffer, range.clone(), cx);
1363        self.xml_tags
1364            .splice(intersecting_tags_range.clone(), new_tags);
1365
1366        // Find which steps intersect the changed range.
1367        let intersecting_steps_range =
1368            self.indices_intersecting_buffer_range(&self.workflow_steps, range.clone(), cx);
1369
1370        // Reparse all tags after the last unchanged step before the change.
1371        let mut tags_start_ix = 0;
1372        if let Some(preceding_unchanged_step) =
1373            self.workflow_steps[..intersecting_steps_range.start].last()
1374        {
1375            tags_start_ix = match self.xml_tags.binary_search_by(|tag| {
1376                tag.range
1377                    .start
1378                    .cmp(&preceding_unchanged_step.range.end, buffer)
1379                    .then(Ordering::Less)
1380            }) {
1381                Ok(ix) | Err(ix) => ix,
1382            };
1383        }
1384
1385        // Rebuild the edit suggestions in the range.
1386        let mut new_steps = self.parse_steps(tags_start_ix, range.end, buffer);
1387
1388        if let Some(project) = self.project() {
1389            for step in &mut new_steps {
1390                Self::resolve_workflow_step_internal(step, &project, cx);
1391            }
1392        }
1393
1394        updated.extend(new_steps.iter().map(|step| step.range.clone()));
1395        let removed_steps = self
1396            .workflow_steps
1397            .splice(intersecting_steps_range, new_steps);
1398        removed.extend(
1399            removed_steps
1400                .map(|step| step.range)
1401                .filter(|range| !updated.contains(&range)),
1402        );
1403    }
1404
1405    fn parse_xml_tags_in_range(
1406        &self,
1407        buffer: &BufferSnapshot,
1408        range: Range<text::Anchor>,
1409        cx: &AppContext,
1410    ) -> Vec<XmlTag> {
1411        let mut messages = self.messages(cx).peekable();
1412
1413        let mut tags = Vec::new();
1414        let mut lines = buffer.text_for_range(range).lines();
1415        let mut offset = lines.offset();
1416
1417        while let Some(line) = lines.next() {
1418            while let Some(message) = messages.peek() {
1419                if offset < message.offset_range.end {
1420                    break;
1421                } else {
1422                    messages.next();
1423                }
1424            }
1425
1426            let is_assistant_message = messages
1427                .peek()
1428                .map_or(false, |message| message.role == Role::Assistant);
1429            if is_assistant_message {
1430                for (start_ix, _) in line.match_indices('<') {
1431                    let mut name_start_ix = start_ix + 1;
1432                    let closing_bracket_ix = line[start_ix..].find('>').map(|i| start_ix + i);
1433                    if let Some(closing_bracket_ix) = closing_bracket_ix {
1434                        let end_ix = closing_bracket_ix + 1;
1435                        let mut is_open_tag = true;
1436                        if line[name_start_ix..closing_bracket_ix].starts_with('/') {
1437                            name_start_ix += 1;
1438                            is_open_tag = false;
1439                        }
1440                        let tag_inner = &line[name_start_ix..closing_bracket_ix];
1441                        let tag_name_len = tag_inner
1442                            .find(|c: char| c.is_whitespace())
1443                            .unwrap_or(tag_inner.len());
1444                        if let Ok(kind) = XmlTagKind::from_str(&tag_inner[..tag_name_len]) {
1445                            tags.push(XmlTag {
1446                                range: buffer.anchor_after(offset + start_ix)
1447                                    ..buffer.anchor_before(offset + end_ix),
1448                                is_open_tag,
1449                                kind,
1450                            });
1451                        };
1452                    }
1453                }
1454            }
1455
1456            offset = lines.offset();
1457        }
1458        tags
1459    }
1460
1461    fn parse_steps(
1462        &mut self,
1463        tags_start_ix: usize,
1464        buffer_end: text::Anchor,
1465        buffer: &BufferSnapshot,
1466    ) -> Vec<WorkflowStep> {
1467        let mut new_steps = Vec::new();
1468        let mut pending_step = None;
1469        let mut edit_step_depth = 0;
1470        let mut tags = self.xml_tags[tags_start_ix..].iter().peekable();
1471        'tags: while let Some(tag) = tags.next() {
1472            if tag.range.start.cmp(&buffer_end, buffer).is_gt() && edit_step_depth == 0 {
1473                break;
1474            }
1475
1476            if tag.kind == XmlTagKind::Step && tag.is_open_tag {
1477                edit_step_depth += 1;
1478                let edit_start = tag.range.start;
1479                let mut edits = Vec::new();
1480                let mut step = WorkflowStep {
1481                    range: edit_start..edit_start,
1482                    leading_tags_end: tag.range.end,
1483                    trailing_tag_start: None,
1484                    edits: Default::default(),
1485                    resolution: None,
1486                    resolution_task: None,
1487                };
1488
1489                while let Some(tag) = tags.next() {
1490                    step.trailing_tag_start.get_or_insert(tag.range.start);
1491
1492                    if tag.kind == XmlTagKind::Step && !tag.is_open_tag {
1493                        // step.trailing_tag_start = Some(tag.range.start);
1494                        edit_step_depth -= 1;
1495                        if edit_step_depth == 0 {
1496                            step.range.end = tag.range.end;
1497                            step.edits = edits.into();
1498                            new_steps.push(step);
1499                            continue 'tags;
1500                        }
1501                    }
1502
1503                    if tag.kind == XmlTagKind::Edit && tag.is_open_tag {
1504                        let mut path = None;
1505                        let mut search = None;
1506                        let mut operation = None;
1507                        let mut description = None;
1508
1509                        while let Some(tag) = tags.next() {
1510                            if tag.kind == XmlTagKind::Edit && !tag.is_open_tag {
1511                                edits.push(WorkflowStepEdit::new(
1512                                    path,
1513                                    operation,
1514                                    search,
1515                                    description,
1516                                ));
1517                                break;
1518                            }
1519
1520                            if tag.is_open_tag
1521                                && [
1522                                    XmlTagKind::Path,
1523                                    XmlTagKind::Search,
1524                                    XmlTagKind::Operation,
1525                                    XmlTagKind::Description,
1526                                ]
1527                                .contains(&tag.kind)
1528                            {
1529                                let kind = tag.kind;
1530                                let content_start = tag.range.end;
1531                                if let Some(tag) = tags.peek() {
1532                                    if tag.kind == kind && !tag.is_open_tag {
1533                                        let tag = tags.next().unwrap();
1534                                        let content_end = tag.range.start;
1535                                        let mut content = buffer
1536                                            .text_for_range(content_start..content_end)
1537                                            .collect::<String>();
1538                                        content.truncate(content.trim_end().len());
1539                                        match kind {
1540                                            XmlTagKind::Path => path = Some(content),
1541                                            XmlTagKind::Operation => operation = Some(content),
1542                                            XmlTagKind::Search => {
1543                                                search = Some(content).filter(|s| !s.is_empty())
1544                                            }
1545                                            XmlTagKind::Description => {
1546                                                description =
1547                                                    Some(content).filter(|s| !s.is_empty())
1548                                            }
1549                                            _ => {}
1550                                        }
1551                                    }
1552                                }
1553                            }
1554                        }
1555                    }
1556                }
1557
1558                pending_step = Some(step);
1559            }
1560        }
1561
1562        if let Some(mut pending_step) = pending_step {
1563            pending_step.range.end = text::Anchor::MAX;
1564            new_steps.push(pending_step);
1565        }
1566
1567        new_steps
1568    }
1569
1570    pub fn resolve_workflow_step(
1571        &mut self,
1572        tagged_range: Range<text::Anchor>,
1573        cx: &mut ModelContext<Self>,
1574    ) -> Option<()> {
1575        let index = self
1576            .workflow_step_index_for_range(&tagged_range, self.buffer.read(cx))
1577            .ok()?;
1578        let step = &mut self.workflow_steps[index];
1579        let project = self.project.as_ref()?;
1580        step.resolution.take();
1581        Self::resolve_workflow_step_internal(step, project, cx);
1582        None
1583    }
1584
1585    fn resolve_workflow_step_internal(
1586        step: &mut WorkflowStep,
1587        project: &Model<Project>,
1588        cx: &mut ModelContext<'_, Context>,
1589    ) {
1590        step.resolution_task = Some(cx.spawn({
1591            let range = step.range.clone();
1592            let edits = step.edits.clone();
1593            let project = project.clone();
1594            |this, mut cx| async move {
1595                let suggestion_groups =
1596                    Self::compute_step_resolution(project, edits, &mut cx).await;
1597
1598                this.update(&mut cx, |this, cx| {
1599                    let buffer = this.buffer.read(cx).text_snapshot();
1600                    let ix = this.workflow_step_index_for_range(&range, &buffer).ok();
1601                    if let Some(ix) = ix {
1602                        let step = &mut this.workflow_steps[ix];
1603
1604                        let resolution = suggestion_groups.map(|suggestion_groups| {
1605                            let mut title = String::new();
1606                            for mut chunk in buffer.text_for_range(
1607                                step.leading_tags_end
1608                                    ..step.trailing_tag_start.unwrap_or(step.range.end),
1609                            ) {
1610                                if title.is_empty() {
1611                                    chunk = chunk.trim_start();
1612                                }
1613                                if let Some((prefix, _)) = chunk.split_once('\n') {
1614                                    title.push_str(prefix);
1615                                    break;
1616                                } else {
1617                                    title.push_str(chunk);
1618                                }
1619                            }
1620
1621                            WorkflowStepResolution {
1622                                title,
1623                                suggestion_groups,
1624                            }
1625                        });
1626
1627                        step.resolution = Some(Arc::new(resolution));
1628                        cx.emit(ContextEvent::WorkflowStepsUpdated {
1629                            removed: vec![],
1630                            updated: vec![range],
1631                        })
1632                    }
1633                })
1634                .ok();
1635            }
1636        }));
1637    }
1638
1639    async fn compute_step_resolution(
1640        project: Model<Project>,
1641        edits: Arc<[Result<WorkflowStepEdit>]>,
1642        cx: &mut AsyncAppContext,
1643    ) -> Result<HashMap<Model<Buffer>, Vec<WorkflowSuggestionGroup>>> {
1644        let mut suggestion_tasks = Vec::new();
1645        for edit in edits.iter() {
1646            let edit = edit.as_ref().map_err(|e| anyhow!("{e}"))?;
1647            suggestion_tasks.push(edit.resolve(project.clone(), cx.clone()));
1648        }
1649
1650        // Expand the context ranges of each suggestion and group suggestions with overlapping context ranges.
1651        let suggestions = future::try_join_all(suggestion_tasks).await?;
1652
1653        let mut suggestions_by_buffer = HashMap::default();
1654        for (buffer, suggestion) in suggestions {
1655            suggestions_by_buffer
1656                .entry(buffer)
1657                .or_insert_with(Vec::new)
1658                .push(suggestion);
1659        }
1660
1661        let mut suggestion_groups_by_buffer = HashMap::default();
1662        for (buffer, mut suggestions) in suggestions_by_buffer {
1663            let mut suggestion_groups = Vec::<WorkflowSuggestionGroup>::new();
1664            let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot())?;
1665            // Sort suggestions by their range so that earlier, larger ranges come first
1666            suggestions.sort_by(|a, b| a.range().cmp(&b.range(), &snapshot));
1667
1668            // Merge overlapping suggestions
1669            suggestions.dedup_by(|a, b| b.try_merge(a, &snapshot));
1670
1671            // Create context ranges for each suggestion
1672            for suggestion in suggestions {
1673                let context_range = {
1674                    let suggestion_point_range = suggestion.range().to_point(&snapshot);
1675                    let start_row = suggestion_point_range.start.row.saturating_sub(5);
1676                    let end_row =
1677                        cmp::min(suggestion_point_range.end.row + 5, snapshot.max_point().row);
1678                    let start = snapshot.anchor_before(Point::new(start_row, 0));
1679                    let end =
1680                        snapshot.anchor_after(Point::new(end_row, snapshot.line_len(end_row)));
1681                    start..end
1682                };
1683
1684                if let Some(last_group) = suggestion_groups.last_mut() {
1685                    if last_group
1686                        .context_range
1687                        .end
1688                        .cmp(&context_range.start, &snapshot)
1689                        .is_ge()
1690                    {
1691                        // Merge with the previous group if context ranges overlap
1692                        last_group.context_range.end = context_range.end;
1693                        last_group.suggestions.push(suggestion);
1694                    } else {
1695                        // Create a new group
1696                        suggestion_groups.push(WorkflowSuggestionGroup {
1697                            context_range,
1698                            suggestions: vec![suggestion],
1699                        });
1700                    }
1701                } else {
1702                    // Create the first group
1703                    suggestion_groups.push(WorkflowSuggestionGroup {
1704                        context_range,
1705                        suggestions: vec![suggestion],
1706                    });
1707                }
1708            }
1709
1710            suggestion_groups_by_buffer.insert(buffer, suggestion_groups);
1711        }
1712
1713        Ok(suggestion_groups_by_buffer)
1714    }
1715
1716    pub fn pending_command_for_position(
1717        &mut self,
1718        position: language::Anchor,
1719        cx: &mut ModelContext<Self>,
1720    ) -> Option<&mut PendingSlashCommand> {
1721        let buffer = self.buffer.read(cx);
1722        match self
1723            .pending_slash_commands
1724            .binary_search_by(|probe| probe.source_range.end.cmp(&position, buffer))
1725        {
1726            Ok(ix) => Some(&mut self.pending_slash_commands[ix]),
1727            Err(ix) => {
1728                let cmd = self.pending_slash_commands.get_mut(ix)?;
1729                if position.cmp(&cmd.source_range.start, buffer).is_ge()
1730                    && position.cmp(&cmd.source_range.end, buffer).is_le()
1731                {
1732                    Some(cmd)
1733                } else {
1734                    None
1735                }
1736            }
1737        }
1738    }
1739
1740    pub fn pending_commands_for_range(
1741        &self,
1742        range: Range<language::Anchor>,
1743        cx: &AppContext,
1744    ) -> &[PendingSlashCommand] {
1745        let range = self.pending_command_indices_for_range(range, cx);
1746        &self.pending_slash_commands[range]
1747    }
1748
1749    fn pending_command_indices_for_range(
1750        &self,
1751        range: Range<language::Anchor>,
1752        cx: &AppContext,
1753    ) -> Range<usize> {
1754        self.indices_intersecting_buffer_range(&self.pending_slash_commands, range, cx)
1755    }
1756
1757    fn indices_intersecting_buffer_range<T: ContextAnnotation>(
1758        &self,
1759        all_annotations: &[T],
1760        range: Range<language::Anchor>,
1761        cx: &AppContext,
1762    ) -> Range<usize> {
1763        let buffer = self.buffer.read(cx);
1764        let start_ix = match all_annotations
1765            .binary_search_by(|probe| probe.range().end.cmp(&range.start, &buffer))
1766        {
1767            Ok(ix) | Err(ix) => ix,
1768        };
1769        let end_ix = match all_annotations
1770            .binary_search_by(|probe| probe.range().start.cmp(&range.end, &buffer))
1771        {
1772            Ok(ix) => ix + 1,
1773            Err(ix) => ix,
1774        };
1775        start_ix..end_ix
1776    }
1777
1778    pub fn insert_command_output(
1779        &mut self,
1780        command_range: Range<language::Anchor>,
1781        output: Task<Result<SlashCommandOutput>>,
1782        ensure_trailing_newline: bool,
1783        expand_result: bool,
1784        cx: &mut ModelContext<Self>,
1785    ) {
1786        self.reparse(cx);
1787
1788        let insert_output_task = cx.spawn(|this, mut cx| {
1789            let command_range = command_range.clone();
1790            async move {
1791                let output = output.await;
1792                this.update(&mut cx, |this, cx| match output {
1793                    Ok(mut output) => {
1794                        // Ensure section ranges are valid.
1795                        for section in &mut output.sections {
1796                            section.range.start = section.range.start.min(output.text.len());
1797                            section.range.end = section.range.end.min(output.text.len());
1798                            while !output.text.is_char_boundary(section.range.start) {
1799                                section.range.start -= 1;
1800                            }
1801                            while !output.text.is_char_boundary(section.range.end) {
1802                                section.range.end += 1;
1803                            }
1804                        }
1805
1806                        // Ensure there is a newline after the last section.
1807                        if ensure_trailing_newline {
1808                            let has_newline_after_last_section =
1809                                output.sections.last().map_or(false, |last_section| {
1810                                    output.text[last_section.range.end..].ends_with('\n')
1811                                });
1812                            if !has_newline_after_last_section {
1813                                output.text.push('\n');
1814                            }
1815                        }
1816
1817                        let version = this.version.clone();
1818                        let command_id = SlashCommandId(this.next_timestamp());
1819                        let (operation, event) = this.buffer.update(cx, |buffer, cx| {
1820                            let start = command_range.start.to_offset(buffer);
1821                            let old_end = command_range.end.to_offset(buffer);
1822                            let new_end = start + output.text.len();
1823                            buffer.edit([(start..old_end, output.text)], None, cx);
1824
1825                            let mut sections = output
1826                                .sections
1827                                .into_iter()
1828                                .map(|section| SlashCommandOutputSection {
1829                                    range: buffer.anchor_after(start + section.range.start)
1830                                        ..buffer.anchor_before(start + section.range.end),
1831                                    icon: section.icon,
1832                                    label: section.label,
1833                                    metadata: section.metadata,
1834                                })
1835                                .collect::<Vec<_>>();
1836                            sections.sort_by(|a, b| a.range.cmp(&b.range, buffer));
1837
1838                            this.slash_command_output_sections
1839                                .extend(sections.iter().cloned());
1840                            this.slash_command_output_sections
1841                                .sort_by(|a, b| a.range.cmp(&b.range, buffer));
1842
1843                            let output_range =
1844                                buffer.anchor_after(start)..buffer.anchor_before(new_end);
1845                            this.finished_slash_commands.insert(command_id);
1846
1847                            (
1848                                ContextOperation::SlashCommandFinished {
1849                                    id: command_id,
1850                                    output_range: output_range.clone(),
1851                                    sections: sections.clone(),
1852                                    version,
1853                                },
1854                                ContextEvent::SlashCommandFinished {
1855                                    output_range,
1856                                    sections,
1857                                    run_commands_in_output: output.run_commands_in_text,
1858                                    expand_result,
1859                                },
1860                            )
1861                        });
1862
1863                        this.push_op(operation, cx);
1864                        cx.emit(event);
1865                    }
1866                    Err(error) => {
1867                        if let Some(pending_command) =
1868                            this.pending_command_for_position(command_range.start, cx)
1869                        {
1870                            pending_command.status =
1871                                PendingSlashCommandStatus::Error(error.to_string());
1872                            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1873                                removed: vec![pending_command.source_range.clone()],
1874                                updated: vec![pending_command.clone()],
1875                            });
1876                        }
1877                    }
1878                })
1879                .ok();
1880            }
1881        });
1882
1883        if let Some(pending_command) = self.pending_command_for_position(command_range.start, cx) {
1884            pending_command.status = PendingSlashCommandStatus::Running {
1885                _task: insert_output_task.shared(),
1886            };
1887            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1888                removed: vec![pending_command.source_range.clone()],
1889                updated: vec![pending_command.clone()],
1890            });
1891        }
1892    }
1893
1894    pub fn insert_tool_output(
1895        &mut self,
1896        tool_use_id: Arc<str>,
1897        output: Task<Result<String>>,
1898        cx: &mut ModelContext<Self>,
1899    ) {
1900        let insert_output_task = cx.spawn(|this, mut cx| {
1901            let tool_use_id = tool_use_id.clone();
1902            async move {
1903                let output = output.await;
1904                this.update(&mut cx, |this, cx| match output {
1905                    Ok(mut output) => {
1906                        const NEWLINE: char = '\n';
1907
1908                        if !output.ends_with(NEWLINE) {
1909                            output.push(NEWLINE);
1910                        }
1911
1912                        let anchor_range = this.buffer.update(cx, |buffer, cx| {
1913                            let insert_start = buffer.len().to_offset(buffer);
1914                            let insert_end = insert_start;
1915
1916                            let start = insert_start;
1917                            let end = start + output.len() - NEWLINE.len_utf8();
1918
1919                            buffer.edit([(insert_start..insert_end, output)], None, cx);
1920
1921                            let output_range = buffer.anchor_after(start)..buffer.anchor_after(end);
1922
1923                            output_range
1924                        });
1925
1926                        this.insert_content(
1927                            Content::ToolResult {
1928                                range: anchor_range.clone(),
1929                                tool_use_id: tool_use_id.clone(),
1930                            },
1931                            cx,
1932                        );
1933
1934                        cx.emit(ContextEvent::ToolFinished {
1935                            tool_use_id,
1936                            output_range: anchor_range,
1937                        });
1938                    }
1939                    Err(err) => {
1940                        if let Some(tool_use) = this.pending_tool_uses_by_id.get_mut(&tool_use_id) {
1941                            tool_use.status = PendingToolUseStatus::Error(err.to_string());
1942                        }
1943                    }
1944                })
1945                .ok();
1946            }
1947        });
1948
1949        if let Some(tool_use) = self.pending_tool_uses_by_id.get_mut(&tool_use_id) {
1950            tool_use.status = PendingToolUseStatus::Running {
1951                _task: insert_output_task.shared(),
1952            };
1953        }
1954    }
1955
1956    pub fn completion_provider_changed(&mut self, cx: &mut ModelContext<Self>) {
1957        self.count_remaining_tokens(cx);
1958    }
1959
1960    fn get_last_valid_message_id(&self, cx: &ModelContext<Self>) -> Option<MessageId> {
1961        self.message_anchors.iter().rev().find_map(|message| {
1962            message
1963                .start
1964                .is_valid(self.buffer.read(cx))
1965                .then_some(message.id)
1966        })
1967    }
1968
1969    pub fn assist(&mut self, cx: &mut ModelContext<Self>) -> Option<MessageAnchor> {
1970        let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
1971        let model = LanguageModelRegistry::read_global(cx).active_model()?;
1972        let last_message_id = self.get_last_valid_message_id(cx)?;
1973
1974        if !provider.is_authenticated(cx) {
1975            log::info!("completion provider has no credentials");
1976            return None;
1977        }
1978        // Compute which messages to cache, including the last one.
1979        self.mark_cache_anchors(&model.cache_configuration(), false, cx);
1980
1981        let mut request = self.to_completion_request(cx);
1982
1983        if cx.has_flag::<ToolUseFeatureFlag>() {
1984            let tool_registry = ToolRegistry::global(cx);
1985            request.tools = tool_registry
1986                .tools()
1987                .into_iter()
1988                .map(|tool| LanguageModelRequestTool {
1989                    name: tool.name(),
1990                    description: tool.description(),
1991                    input_schema: tool.input_schema(),
1992                })
1993                .collect();
1994        }
1995
1996        let assistant_message = self
1997            .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1998            .unwrap();
1999
2000        // Queue up the user's next reply.
2001        let user_message = self
2002            .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
2003            .unwrap();
2004
2005        let pending_completion_id = post_inc(&mut self.completion_count);
2006
2007        let task = cx.spawn({
2008            |this, mut cx| async move {
2009                let stream = model.stream_completion(request, &cx);
2010                let assistant_message_id = assistant_message.id;
2011                let mut response_latency = None;
2012                let stream_completion = async {
2013                    let request_start = Instant::now();
2014                    let mut events = stream.await?;
2015                    let mut stop_reason = StopReason::EndTurn;
2016
2017                    while let Some(event) = events.next().await {
2018                        if response_latency.is_none() {
2019                            response_latency = Some(request_start.elapsed());
2020                        }
2021                        let event = event?;
2022
2023                        this.update(&mut cx, |this, cx| {
2024                            let message_ix = this
2025                                .message_anchors
2026                                .iter()
2027                                .position(|message| message.id == assistant_message_id)?;
2028                            this.buffer.update(cx, |buffer, cx| {
2029                                let message_old_end_offset = this.message_anchors[message_ix + 1..]
2030                                    .iter()
2031                                    .find(|message| message.start.is_valid(buffer))
2032                                    .map_or(buffer.len(), |message| {
2033                                        message.start.to_offset(buffer).saturating_sub(1)
2034                                    });
2035
2036                                match event {
2037                                    LanguageModelCompletionEvent::Stop(reason) => {
2038                                        stop_reason = reason;
2039                                    }
2040                                    LanguageModelCompletionEvent::Text(chunk) => {
2041                                        buffer.edit(
2042                                            [(
2043                                                message_old_end_offset..message_old_end_offset,
2044                                                chunk,
2045                                            )],
2046                                            None,
2047                                            cx,
2048                                        );
2049                                    }
2050                                    LanguageModelCompletionEvent::ToolUse(tool_use) => {
2051                                        const NEWLINE: char = '\n';
2052
2053                                        let mut text = String::new();
2054                                        text.push(NEWLINE);
2055                                        text.push_str(
2056                                            &serde_json::to_string_pretty(&tool_use)
2057                                                .expect("failed to serialize tool use to JSON"),
2058                                        );
2059                                        text.push(NEWLINE);
2060                                        let text_len = text.len();
2061
2062                                        buffer.edit(
2063                                            [(
2064                                                message_old_end_offset..message_old_end_offset,
2065                                                text,
2066                                            )],
2067                                            None,
2068                                            cx,
2069                                        );
2070
2071                                        let start_ix = message_old_end_offset + NEWLINE.len_utf8();
2072                                        let end_ix =
2073                                            message_old_end_offset + text_len - NEWLINE.len_utf8();
2074                                        let source_range = buffer.anchor_after(start_ix)
2075                                            ..buffer.anchor_after(end_ix);
2076
2077                                        let tool_use_id: Arc<str> = tool_use.id.into();
2078                                        this.pending_tool_uses_by_id.insert(
2079                                            tool_use_id.clone(),
2080                                            PendingToolUse {
2081                                                id: tool_use_id,
2082                                                name: tool_use.name,
2083                                                input: tool_use.input,
2084                                                status: PendingToolUseStatus::Idle,
2085                                                source_range,
2086                                            },
2087                                        );
2088                                    }
2089                                }
2090                            });
2091
2092                            cx.emit(ContextEvent::StreamedCompletion);
2093
2094                            Some(())
2095                        })?;
2096                        smol::future::yield_now().await;
2097                    }
2098                    this.update(&mut cx, |this, cx| {
2099                        this.pending_completions
2100                            .retain(|completion| completion.id != pending_completion_id);
2101                        this.summarize(false, cx);
2102                        this.update_cache_status_for_completion(cx);
2103                    })?;
2104
2105                    anyhow::Ok(stop_reason)
2106                };
2107
2108                let result = stream_completion.await;
2109
2110                this.update(&mut cx, |this, cx| {
2111                    let error_message = result
2112                        .as_ref()
2113                        .err()
2114                        .map(|error| error.to_string().trim().to_string());
2115
2116                    if let Some(error_message) = error_message.as_ref() {
2117                        cx.emit(ContextEvent::ShowAssistError(SharedString::from(
2118                            error_message.clone(),
2119                        )));
2120                    }
2121
2122                    this.update_metadata(assistant_message_id, cx, |metadata| {
2123                        if let Some(error_message) = error_message.as_ref() {
2124                            metadata.status =
2125                                MessageStatus::Error(SharedString::from(error_message.clone()));
2126                        } else {
2127                            metadata.status = MessageStatus::Done;
2128                        }
2129                    });
2130
2131                    if let Some(telemetry) = this.telemetry.as_ref() {
2132                        telemetry.report_assistant_event(
2133                            Some(this.id.0.clone()),
2134                            AssistantKind::Panel,
2135                            AssistantPhase::Response,
2136                            model.telemetry_id(),
2137                            response_latency,
2138                            error_message,
2139                        );
2140                    }
2141
2142                    if let Ok(stop_reason) = result {
2143                        match stop_reason {
2144                            StopReason::ToolUse => {
2145                                cx.emit(ContextEvent::UsePendingTools);
2146                            }
2147                            StopReason::EndTurn => {}
2148                            StopReason::MaxTokens => {}
2149                        }
2150                    }
2151                })
2152                .ok();
2153            }
2154        });
2155
2156        self.pending_completions.push(PendingCompletion {
2157            id: pending_completion_id,
2158            assistant_message_id: assistant_message.id,
2159            _task: task,
2160        });
2161
2162        Some(user_message)
2163    }
2164
2165    pub fn to_completion_request(&self, cx: &AppContext) -> LanguageModelRequest {
2166        let buffer = self.buffer.read(cx);
2167
2168        let mut contents = self.contents(cx).peekable();
2169
2170        fn collect_text_content(buffer: &Buffer, range: Range<usize>) -> Option<String> {
2171            let text: String = buffer.text_for_range(range.clone()).collect();
2172            if text.trim().is_empty() {
2173                None
2174            } else {
2175                Some(text)
2176            }
2177        }
2178
2179        let mut completion_request = LanguageModelRequest {
2180            messages: Vec::new(),
2181            tools: Vec::new(),
2182            stop: Vec::new(),
2183            temperature: 1.0,
2184        };
2185        for message in self.messages(cx) {
2186            if message.status != MessageStatus::Done {
2187                continue;
2188            }
2189
2190            let mut offset = message.offset_range.start;
2191            let mut request_message = LanguageModelRequestMessage {
2192                role: message.role,
2193                content: Vec::new(),
2194                cache: message
2195                    .cache
2196                    .as_ref()
2197                    .map_or(false, |cache| cache.is_anchor),
2198            };
2199
2200            while let Some(content) = contents.peek() {
2201                if content
2202                    .range()
2203                    .end
2204                    .cmp(&message.anchor_range.end, buffer)
2205                    .is_lt()
2206                {
2207                    let content = contents.next().unwrap();
2208                    let range = content.range().to_offset(buffer);
2209                    request_message.content.extend(
2210                        collect_text_content(buffer, offset..range.start).map(MessageContent::Text),
2211                    );
2212
2213                    match content {
2214                        Content::Image { image, .. } => {
2215                            if let Some(image) = image.clone().now_or_never().flatten() {
2216                                request_message
2217                                    .content
2218                                    .push(language_model::MessageContent::Image(image));
2219                            }
2220                        }
2221                        Content::ToolUse { tool_use, .. } => {
2222                            request_message
2223                                .content
2224                                .push(language_model::MessageContent::ToolUse(tool_use.clone()));
2225                        }
2226                        Content::ToolResult { tool_use_id, .. } => {
2227                            request_message.content.push(
2228                                language_model::MessageContent::ToolResult(
2229                                    LanguageModelToolResult {
2230                                        tool_use_id: tool_use_id.to_string(),
2231                                        is_error: false,
2232                                        content: collect_text_content(buffer, range.clone())
2233                                            .unwrap_or_default(),
2234                                    },
2235                                ),
2236                            );
2237                        }
2238                    }
2239
2240                    offset = range.end;
2241                } else {
2242                    break;
2243                }
2244            }
2245
2246            request_message.content.extend(
2247                collect_text_content(buffer, offset..message.offset_range.end)
2248                    .map(MessageContent::Text),
2249            );
2250
2251            completion_request.messages.push(request_message);
2252        }
2253
2254        completion_request
2255    }
2256
2257    pub fn cancel_last_assist(&mut self, cx: &mut ModelContext<Self>) -> bool {
2258        if let Some(pending_completion) = self.pending_completions.pop() {
2259            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
2260                if metadata.status == MessageStatus::Pending {
2261                    metadata.status = MessageStatus::Canceled;
2262                }
2263            });
2264            true
2265        } else {
2266            false
2267        }
2268    }
2269
2270    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
2271        for id in &ids {
2272            if let Some(metadata) = self.messages_metadata.get(id) {
2273                let role = metadata.role.cycle();
2274                self.update_metadata(*id, cx, |metadata| metadata.role = role);
2275            }
2276        }
2277
2278        self.message_roles_updated(ids, cx);
2279    }
2280
2281    fn message_roles_updated(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
2282        let mut ranges = Vec::new();
2283        for message in self.messages(cx) {
2284            if ids.contains(&message.id) {
2285                ranges.push(message.anchor_range.clone());
2286            }
2287        }
2288
2289        let buffer = self.buffer.read(cx).text_snapshot();
2290        let mut updated = Vec::new();
2291        let mut removed = Vec::new();
2292        for range in ranges {
2293            self.reparse_workflow_steps_in_range(range, &buffer, &mut updated, &mut removed, cx);
2294        }
2295
2296        if !updated.is_empty() || !removed.is_empty() {
2297            cx.emit(ContextEvent::WorkflowStepsUpdated { removed, updated })
2298        }
2299    }
2300
2301    pub fn update_metadata(
2302        &mut self,
2303        id: MessageId,
2304        cx: &mut ModelContext<Self>,
2305        f: impl FnOnce(&mut MessageMetadata),
2306    ) {
2307        let version = self.version.clone();
2308        let timestamp = self.next_timestamp();
2309        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
2310            f(metadata);
2311            metadata.timestamp = timestamp;
2312            let operation = ContextOperation::UpdateMessage {
2313                message_id: id,
2314                metadata: metadata.clone(),
2315                version,
2316            };
2317            self.push_op(operation, cx);
2318            cx.emit(ContextEvent::MessagesEdited);
2319            cx.notify();
2320        }
2321    }
2322
2323    pub fn insert_message_after(
2324        &mut self,
2325        message_id: MessageId,
2326        role: Role,
2327        status: MessageStatus,
2328        cx: &mut ModelContext<Self>,
2329    ) -> Option<MessageAnchor> {
2330        if let Some(prev_message_ix) = self
2331            .message_anchors
2332            .iter()
2333            .position(|message| message.id == message_id)
2334        {
2335            // Find the next valid message after the one we were given.
2336            let mut next_message_ix = prev_message_ix + 1;
2337            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
2338                if next_message.start.is_valid(self.buffer.read(cx)) {
2339                    break;
2340                }
2341                next_message_ix += 1;
2342            }
2343
2344            let start = self.buffer.update(cx, |buffer, cx| {
2345                let offset = self
2346                    .message_anchors
2347                    .get(next_message_ix)
2348                    .map_or(buffer.len(), |message| {
2349                        buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
2350                    });
2351                buffer.edit([(offset..offset, "\n")], None, cx);
2352                buffer.anchor_before(offset + 1)
2353            });
2354
2355            let version = self.version.clone();
2356            let anchor = MessageAnchor {
2357                id: MessageId(self.next_timestamp()),
2358                start,
2359            };
2360            let metadata = MessageMetadata {
2361                role,
2362                status,
2363                timestamp: anchor.id.0,
2364                cache: None,
2365            };
2366            self.insert_message(anchor.clone(), metadata.clone(), cx);
2367            self.push_op(
2368                ContextOperation::InsertMessage {
2369                    anchor: anchor.clone(),
2370                    metadata,
2371                    version,
2372                },
2373                cx,
2374            );
2375            Some(anchor)
2376        } else {
2377            None
2378        }
2379    }
2380
2381    pub fn insert_content(&mut self, content: Content, cx: &mut ModelContext<Self>) {
2382        let buffer = self.buffer.read(cx);
2383        let insertion_ix = match self
2384            .contents
2385            .binary_search_by(|probe| probe.cmp(&content, buffer))
2386        {
2387            Ok(ix) => {
2388                self.contents.remove(ix);
2389                ix
2390            }
2391            Err(ix) => ix,
2392        };
2393        self.contents.insert(insertion_ix, content);
2394        cx.emit(ContextEvent::MessagesEdited);
2395    }
2396
2397    pub fn contents<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Content> {
2398        let buffer = self.buffer.read(cx);
2399        self.contents
2400            .iter()
2401            .filter(|content| {
2402                let range = content.range();
2403                range.start.is_valid(buffer) && range.end.is_valid(buffer)
2404            })
2405            .cloned()
2406    }
2407
2408    pub fn split_message(
2409        &mut self,
2410        range: Range<usize>,
2411        cx: &mut ModelContext<Self>,
2412    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
2413        let start_message = self.message_for_offset(range.start, cx);
2414        let end_message = self.message_for_offset(range.end, cx);
2415        if let Some((start_message, end_message)) = start_message.zip(end_message) {
2416            // Prevent splitting when range spans multiple messages.
2417            if start_message.id != end_message.id {
2418                return (None, None);
2419            }
2420
2421            let message = start_message;
2422            let role = message.role;
2423            let mut edited_buffer = false;
2424
2425            let mut suffix_start = None;
2426
2427            // TODO: why did this start panicking?
2428            if range.start > message.offset_range.start
2429                && range.end < message.offset_range.end.saturating_sub(1)
2430            {
2431                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2432                    suffix_start = Some(range.end + 1);
2433                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2434                    suffix_start = Some(range.end);
2435                }
2436            }
2437
2438            let version = self.version.clone();
2439            let suffix = if let Some(suffix_start) = suffix_start {
2440                MessageAnchor {
2441                    id: MessageId(self.next_timestamp()),
2442                    start: self.buffer.read(cx).anchor_before(suffix_start),
2443                }
2444            } else {
2445                self.buffer.update(cx, |buffer, cx| {
2446                    buffer.edit([(range.end..range.end, "\n")], None, cx);
2447                });
2448                edited_buffer = true;
2449                MessageAnchor {
2450                    id: MessageId(self.next_timestamp()),
2451                    start: self.buffer.read(cx).anchor_before(range.end + 1),
2452                }
2453            };
2454
2455            let suffix_metadata = MessageMetadata {
2456                role,
2457                status: MessageStatus::Done,
2458                timestamp: suffix.id.0,
2459                cache: None,
2460            };
2461            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2462            self.push_op(
2463                ContextOperation::InsertMessage {
2464                    anchor: suffix.clone(),
2465                    metadata: suffix_metadata,
2466                    version,
2467                },
2468                cx,
2469            );
2470
2471            let new_messages =
2472                if range.start == range.end || range.start == message.offset_range.start {
2473                    (None, Some(suffix))
2474                } else {
2475                    let mut prefix_end = None;
2476                    if range.start > message.offset_range.start
2477                        && range.end < message.offset_range.end - 1
2478                    {
2479                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2480                            prefix_end = Some(range.start + 1);
2481                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2482                            == Some('\n')
2483                        {
2484                            prefix_end = Some(range.start);
2485                        }
2486                    }
2487
2488                    let version = self.version.clone();
2489                    let selection = if let Some(prefix_end) = prefix_end {
2490                        MessageAnchor {
2491                            id: MessageId(self.next_timestamp()),
2492                            start: self.buffer.read(cx).anchor_before(prefix_end),
2493                        }
2494                    } else {
2495                        self.buffer.update(cx, |buffer, cx| {
2496                            buffer.edit([(range.start..range.start, "\n")], None, cx)
2497                        });
2498                        edited_buffer = true;
2499                        MessageAnchor {
2500                            id: MessageId(self.next_timestamp()),
2501                            start: self.buffer.read(cx).anchor_before(range.end + 1),
2502                        }
2503                    };
2504
2505                    let selection_metadata = MessageMetadata {
2506                        role,
2507                        status: MessageStatus::Done,
2508                        timestamp: selection.id.0,
2509                        cache: None,
2510                    };
2511                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2512                    self.push_op(
2513                        ContextOperation::InsertMessage {
2514                            anchor: selection.clone(),
2515                            metadata: selection_metadata,
2516                            version,
2517                        },
2518                        cx,
2519                    );
2520
2521                    (Some(selection), Some(suffix))
2522                };
2523
2524            if !edited_buffer {
2525                cx.emit(ContextEvent::MessagesEdited);
2526            }
2527            new_messages
2528        } else {
2529            (None, None)
2530        }
2531    }
2532
2533    fn insert_message(
2534        &mut self,
2535        new_anchor: MessageAnchor,
2536        new_metadata: MessageMetadata,
2537        cx: &mut ModelContext<Self>,
2538    ) {
2539        cx.emit(ContextEvent::MessagesEdited);
2540
2541        self.messages_metadata.insert(new_anchor.id, new_metadata);
2542
2543        let buffer = self.buffer.read(cx);
2544        let insertion_ix = self
2545            .message_anchors
2546            .iter()
2547            .position(|anchor| {
2548                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2549                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2550            })
2551            .unwrap_or(self.message_anchors.len());
2552        self.message_anchors.insert(insertion_ix, new_anchor);
2553    }
2554
2555    pub(super) fn summarize(&mut self, replace_old: bool, cx: &mut ModelContext<Self>) {
2556        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
2557            return;
2558        };
2559        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
2560            return;
2561        };
2562
2563        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
2564            if !provider.is_authenticated(cx) {
2565                return;
2566            }
2567
2568            let mut request = self.to_completion_request(cx);
2569            request.messages.push(LanguageModelRequestMessage {
2570                role: Role::User,
2571                content: vec![
2572                    "Summarize the context into a short title without punctuation.".into(),
2573                ],
2574                cache: false,
2575            });
2576
2577            self.pending_summary = cx.spawn(|this, mut cx| {
2578                async move {
2579                    let stream = model.stream_completion_text(request, &cx);
2580                    let mut messages = stream.await?;
2581
2582                    let mut replaced = !replace_old;
2583                    while let Some(message) = messages.next().await {
2584                        let text = message?;
2585                        let mut lines = text.lines();
2586                        this.update(&mut cx, |this, cx| {
2587                            let version = this.version.clone();
2588                            let timestamp = this.next_timestamp();
2589                            let summary = this.summary.get_or_insert(ContextSummary::default());
2590                            if !replaced && replace_old {
2591                                summary.text.clear();
2592                                replaced = true;
2593                            }
2594                            summary.text.extend(lines.next());
2595                            summary.timestamp = timestamp;
2596                            let operation = ContextOperation::UpdateSummary {
2597                                summary: summary.clone(),
2598                                version,
2599                            };
2600                            this.push_op(operation, cx);
2601                            cx.emit(ContextEvent::SummaryChanged);
2602                        })?;
2603
2604                        // Stop if the LLM generated multiple lines.
2605                        if lines.next().is_some() {
2606                            break;
2607                        }
2608                    }
2609
2610                    this.update(&mut cx, |this, cx| {
2611                        let version = this.version.clone();
2612                        let timestamp = this.next_timestamp();
2613                        if let Some(summary) = this.summary.as_mut() {
2614                            summary.done = true;
2615                            summary.timestamp = timestamp;
2616                            let operation = ContextOperation::UpdateSummary {
2617                                summary: summary.clone(),
2618                                version,
2619                            };
2620                            this.push_op(operation, cx);
2621                            cx.emit(ContextEvent::SummaryChanged);
2622                        }
2623                    })?;
2624
2625                    anyhow::Ok(())
2626                }
2627                .log_err()
2628            });
2629        }
2630    }
2631
2632    fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
2633        self.messages_for_offsets([offset], cx).pop()
2634    }
2635
2636    pub fn messages_for_offsets(
2637        &self,
2638        offsets: impl IntoIterator<Item = usize>,
2639        cx: &AppContext,
2640    ) -> Vec<Message> {
2641        let mut result = Vec::new();
2642
2643        let mut messages = self.messages(cx).peekable();
2644        let mut offsets = offsets.into_iter().peekable();
2645        let mut current_message = messages.next();
2646        while let Some(offset) = offsets.next() {
2647            // Locate the message that contains the offset.
2648            while current_message.as_ref().map_or(false, |message| {
2649                !message.offset_range.contains(&offset) && messages.peek().is_some()
2650            }) {
2651                current_message = messages.next();
2652            }
2653            let Some(message) = current_message.as_ref() else {
2654                break;
2655            };
2656
2657            // Skip offsets that are in the same message.
2658            while offsets.peek().map_or(false, |offset| {
2659                message.offset_range.contains(offset) || messages.peek().is_none()
2660            }) {
2661                offsets.next();
2662            }
2663
2664            result.push(message.clone());
2665        }
2666        result
2667    }
2668
2669    fn messages_from_anchors<'a>(
2670        &'a self,
2671        message_anchors: impl Iterator<Item = &'a MessageAnchor> + 'a,
2672        cx: &'a AppContext,
2673    ) -> impl 'a + Iterator<Item = Message> {
2674        let buffer = self.buffer.read(cx);
2675
2676        Self::messages_from_iters(buffer, &self.messages_metadata, message_anchors.enumerate())
2677    }
2678
2679    pub fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
2680        self.messages_from_anchors(self.message_anchors.iter(), cx)
2681    }
2682
2683    pub fn messages_from_iters<'a>(
2684        buffer: &'a Buffer,
2685        metadata: &'a HashMap<MessageId, MessageMetadata>,
2686        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2687    ) -> impl 'a + Iterator<Item = Message> {
2688        let mut messages = messages.peekable();
2689
2690        iter::from_fn(move || {
2691            if let Some((start_ix, message_anchor)) = messages.next() {
2692                let metadata = metadata.get(&message_anchor.id)?;
2693
2694                let message_start = message_anchor.start.to_offset(buffer);
2695                let mut message_end = None;
2696                let mut end_ix = start_ix;
2697                while let Some((_, next_message)) = messages.peek() {
2698                    if next_message.start.is_valid(buffer) {
2699                        message_end = Some(next_message.start);
2700                        break;
2701                    } else {
2702                        end_ix += 1;
2703                        messages.next();
2704                    }
2705                }
2706                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2707                let message_end = message_end_anchor.to_offset(buffer);
2708
2709                return Some(Message {
2710                    index_range: start_ix..end_ix,
2711                    offset_range: message_start..message_end,
2712                    anchor_range: message_anchor.start..message_end_anchor,
2713                    id: message_anchor.id,
2714                    role: metadata.role,
2715                    status: metadata.status.clone(),
2716                    cache: metadata.cache.clone(),
2717                });
2718            }
2719            None
2720        })
2721    }
2722
2723    pub fn save(
2724        &mut self,
2725        debounce: Option<Duration>,
2726        fs: Arc<dyn Fs>,
2727        cx: &mut ModelContext<Context>,
2728    ) {
2729        if self.replica_id() != ReplicaId::default() {
2730            // Prevent saving a remote context for now.
2731            return;
2732        }
2733
2734        self.pending_save = cx.spawn(|this, mut cx| async move {
2735            if let Some(debounce) = debounce {
2736                cx.background_executor().timer(debounce).await;
2737            }
2738
2739            let (old_path, summary) = this.read_with(&cx, |this, _| {
2740                let path = this.path.clone();
2741                let summary = if let Some(summary) = this.summary.as_ref() {
2742                    if summary.done {
2743                        Some(summary.text.clone())
2744                    } else {
2745                        None
2746                    }
2747                } else {
2748                    None
2749                };
2750                (path, summary)
2751            })?;
2752
2753            if let Some(summary) = summary {
2754                let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2755                let mut discriminant = 1;
2756                let mut new_path;
2757                loop {
2758                    new_path = contexts_dir().join(&format!(
2759                        "{} - {}.zed.json",
2760                        summary.trim(),
2761                        discriminant
2762                    ));
2763                    if fs.is_file(&new_path).await {
2764                        discriminant += 1;
2765                    } else {
2766                        break;
2767                    }
2768                }
2769
2770                fs.create_dir(contexts_dir().as_ref()).await?;
2771                fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
2772                    .await?;
2773                if let Some(old_path) = old_path {
2774                    if new_path != old_path {
2775                        fs.remove_file(
2776                            &old_path,
2777                            RemoveOptions {
2778                                recursive: false,
2779                                ignore_if_not_exists: true,
2780                            },
2781                        )
2782                        .await?;
2783                    }
2784                }
2785
2786                this.update(&mut cx, |this, _| this.path = Some(new_path))?;
2787            }
2788
2789            Ok(())
2790        });
2791    }
2792
2793    pub(crate) fn custom_summary(&mut self, custom_summary: String, cx: &mut ModelContext<Self>) {
2794        let timestamp = self.next_timestamp();
2795        let summary = self.summary.get_or_insert(ContextSummary::default());
2796        summary.timestamp = timestamp;
2797        summary.done = true;
2798        summary.text = custom_summary;
2799        cx.emit(ContextEvent::SummaryChanged);
2800    }
2801}
2802
2803#[derive(Debug, Default)]
2804pub struct ContextVersion {
2805    context: clock::Global,
2806    buffer: clock::Global,
2807}
2808
2809impl ContextVersion {
2810    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2811        Self {
2812            context: language::proto::deserialize_version(&proto.context_version),
2813            buffer: language::proto::deserialize_version(&proto.buffer_version),
2814        }
2815    }
2816
2817    pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
2818        proto::ContextVersion {
2819            context_id: context_id.to_proto(),
2820            context_version: language::proto::serialize_version(&self.context),
2821            buffer_version: language::proto::serialize_version(&self.buffer),
2822        }
2823    }
2824}
2825
2826#[derive(Debug, Clone)]
2827pub struct PendingSlashCommand {
2828    pub name: String,
2829    pub arguments: SmallVec<[String; 3]>,
2830    pub status: PendingSlashCommandStatus,
2831    pub source_range: Range<language::Anchor>,
2832}
2833
2834#[derive(Debug, Clone)]
2835pub enum PendingSlashCommandStatus {
2836    Idle,
2837    Running { _task: Shared<Task<()>> },
2838    Error(String),
2839}
2840
2841pub(crate) struct ToolUseFeatureFlag;
2842
2843impl FeatureFlag for ToolUseFeatureFlag {
2844    const NAME: &'static str = "assistant-tool-use";
2845
2846    fn enabled_for_staff() -> bool {
2847        false
2848    }
2849}
2850
2851#[derive(Debug, Clone)]
2852pub struct PendingToolUse {
2853    pub id: Arc<str>,
2854    pub name: String,
2855    pub input: serde_json::Value,
2856    pub status: PendingToolUseStatus,
2857    pub source_range: Range<language::Anchor>,
2858}
2859
2860#[derive(Debug, Clone)]
2861pub enum PendingToolUseStatus {
2862    Idle,
2863    Running { _task: Shared<Task<()>> },
2864    Error(String),
2865}
2866
2867impl PendingToolUseStatus {
2868    pub fn is_idle(&self) -> bool {
2869        matches!(self, PendingToolUseStatus::Idle)
2870    }
2871}
2872
2873#[derive(Serialize, Deserialize)]
2874pub struct SavedMessage {
2875    pub id: MessageId,
2876    pub start: usize,
2877    pub metadata: MessageMetadata,
2878}
2879
2880#[derive(Serialize, Deserialize)]
2881pub struct SavedContext {
2882    pub id: Option<ContextId>,
2883    pub zed: String,
2884    pub version: String,
2885    pub text: String,
2886    pub messages: Vec<SavedMessage>,
2887    pub summary: String,
2888    pub slash_command_output_sections:
2889        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2890}
2891
2892impl SavedContext {
2893    pub const VERSION: &'static str = "0.4.0";
2894
2895    pub fn from_json(json: &str) -> Result<Self> {
2896        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
2897        match saved_context_json
2898            .get("version")
2899            .ok_or_else(|| anyhow!("version not found"))?
2900        {
2901            serde_json::Value::String(version) => match version.as_str() {
2902                SavedContext::VERSION => {
2903                    Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
2904                }
2905                SavedContextV0_3_0::VERSION => {
2906                    let saved_context =
2907                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
2908                    Ok(saved_context.upgrade())
2909                }
2910                SavedContextV0_2_0::VERSION => {
2911                    let saved_context =
2912                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
2913                    Ok(saved_context.upgrade())
2914                }
2915                SavedContextV0_1_0::VERSION => {
2916                    let saved_context =
2917                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
2918                    Ok(saved_context.upgrade())
2919                }
2920                _ => Err(anyhow!("unrecognized saved context version: {}", version)),
2921            },
2922            _ => Err(anyhow!("version not found on saved context")),
2923        }
2924    }
2925
2926    fn into_ops(
2927        self,
2928        buffer: &Model<Buffer>,
2929        cx: &mut ModelContext<Context>,
2930    ) -> Vec<ContextOperation> {
2931        let mut operations = Vec::new();
2932        let mut version = clock::Global::new();
2933        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
2934
2935        let mut first_message_metadata = None;
2936        for message in self.messages {
2937            if message.id == MessageId(clock::Lamport::default()) {
2938                first_message_metadata = Some(message.metadata);
2939            } else {
2940                operations.push(ContextOperation::InsertMessage {
2941                    anchor: MessageAnchor {
2942                        id: message.id,
2943                        start: buffer.read(cx).anchor_before(message.start),
2944                    },
2945                    metadata: MessageMetadata {
2946                        role: message.metadata.role,
2947                        status: message.metadata.status,
2948                        timestamp: message.metadata.timestamp,
2949                        cache: None,
2950                    },
2951                    version: version.clone(),
2952                });
2953                version.observe(message.id.0);
2954                next_timestamp.observe(message.id.0);
2955            }
2956        }
2957
2958        if let Some(metadata) = first_message_metadata {
2959            let timestamp = next_timestamp.tick();
2960            operations.push(ContextOperation::UpdateMessage {
2961                message_id: MessageId(clock::Lamport::default()),
2962                metadata: MessageMetadata {
2963                    role: metadata.role,
2964                    status: metadata.status,
2965                    timestamp,
2966                    cache: None,
2967                },
2968                version: version.clone(),
2969            });
2970            version.observe(timestamp);
2971        }
2972
2973        let timestamp = next_timestamp.tick();
2974        operations.push(ContextOperation::SlashCommandFinished {
2975            id: SlashCommandId(timestamp),
2976            output_range: language::Anchor::MIN..language::Anchor::MAX,
2977            sections: self
2978                .slash_command_output_sections
2979                .into_iter()
2980                .map(|section| {
2981                    let buffer = buffer.read(cx);
2982                    SlashCommandOutputSection {
2983                        range: buffer.anchor_after(section.range.start)
2984                            ..buffer.anchor_before(section.range.end),
2985                        icon: section.icon,
2986                        label: section.label,
2987                        metadata: section.metadata,
2988                    }
2989                })
2990                .collect(),
2991            version: version.clone(),
2992        });
2993        version.observe(timestamp);
2994
2995        let timestamp = next_timestamp.tick();
2996        operations.push(ContextOperation::UpdateSummary {
2997            summary: ContextSummary {
2998                text: self.summary,
2999                done: true,
3000                timestamp,
3001            },
3002            version: version.clone(),
3003        });
3004        version.observe(timestamp);
3005
3006        operations
3007    }
3008}
3009
3010#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3011struct SavedMessageIdPreV0_4_0(usize);
3012
3013#[derive(Serialize, Deserialize)]
3014struct SavedMessagePreV0_4_0 {
3015    id: SavedMessageIdPreV0_4_0,
3016    start: usize,
3017}
3018
3019#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3020struct SavedMessageMetadataPreV0_4_0 {
3021    role: Role,
3022    status: MessageStatus,
3023}
3024
3025#[derive(Serialize, Deserialize)]
3026struct SavedContextV0_3_0 {
3027    id: Option<ContextId>,
3028    zed: String,
3029    version: String,
3030    text: String,
3031    messages: Vec<SavedMessagePreV0_4_0>,
3032    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3033    summary: String,
3034    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
3035}
3036
3037impl SavedContextV0_3_0 {
3038    const VERSION: &'static str = "0.3.0";
3039
3040    fn upgrade(self) -> SavedContext {
3041        SavedContext {
3042            id: self.id,
3043            zed: self.zed,
3044            version: SavedContext::VERSION.into(),
3045            text: self.text,
3046            messages: self
3047                .messages
3048                .into_iter()
3049                .filter_map(|message| {
3050                    let metadata = self.message_metadata.get(&message.id)?;
3051                    let timestamp = clock::Lamport {
3052                        replica_id: ReplicaId::default(),
3053                        value: message.id.0 as u32,
3054                    };
3055                    Some(SavedMessage {
3056                        id: MessageId(timestamp),
3057                        start: message.start,
3058                        metadata: MessageMetadata {
3059                            role: metadata.role,
3060                            status: metadata.status.clone(),
3061                            timestamp,
3062                            cache: None,
3063                        },
3064                    })
3065                })
3066                .collect(),
3067            summary: self.summary,
3068            slash_command_output_sections: self.slash_command_output_sections,
3069        }
3070    }
3071}
3072
3073#[derive(Serialize, Deserialize)]
3074struct SavedContextV0_2_0 {
3075    id: Option<ContextId>,
3076    zed: String,
3077    version: String,
3078    text: String,
3079    messages: Vec<SavedMessagePreV0_4_0>,
3080    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3081    summary: String,
3082}
3083
3084impl SavedContextV0_2_0 {
3085    const VERSION: &'static str = "0.2.0";
3086
3087    fn upgrade(self) -> SavedContext {
3088        SavedContextV0_3_0 {
3089            id: self.id,
3090            zed: self.zed,
3091            version: SavedContextV0_3_0::VERSION.to_string(),
3092            text: self.text,
3093            messages: self.messages,
3094            message_metadata: self.message_metadata,
3095            summary: self.summary,
3096            slash_command_output_sections: Vec::new(),
3097        }
3098        .upgrade()
3099    }
3100}
3101
3102#[derive(Serialize, Deserialize)]
3103struct SavedContextV0_1_0 {
3104    id: Option<ContextId>,
3105    zed: String,
3106    version: String,
3107    text: String,
3108    messages: Vec<SavedMessagePreV0_4_0>,
3109    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
3110    summary: String,
3111    api_url: Option<String>,
3112    model: OpenAiModel,
3113}
3114
3115impl SavedContextV0_1_0 {
3116    const VERSION: &'static str = "0.1.0";
3117
3118    fn upgrade(self) -> SavedContext {
3119        SavedContextV0_2_0 {
3120            id: self.id,
3121            zed: self.zed,
3122            version: SavedContextV0_2_0::VERSION.to_string(),
3123            text: self.text,
3124            messages: self.messages,
3125            message_metadata: self.message_metadata,
3126            summary: self.summary,
3127        }
3128        .upgrade()
3129    }
3130}
3131
3132#[derive(Clone)]
3133pub struct SavedContextMetadata {
3134    pub title: String,
3135    pub path: PathBuf,
3136    pub mtime: chrono::DateTime<chrono::Local>,
3137}