context.rs

   1use crate::{
   2    prompts::PromptBuilder, slash_command::SlashCommandLine, AssistantPanel, InitialInsertion,
   3    InlineAssistId, InlineAssistant, MessageId, MessageStatus,
   4};
   5use anyhow::{anyhow, Context as _, Result};
   6use assistant_slash_command::{
   7    SlashCommandOutput, SlashCommandOutputSection, SlashCommandRegistry,
   8};
   9use client::{self, proto, telemetry::Telemetry};
  10use clock::ReplicaId;
  11use collections::{HashMap, HashSet};
  12use editor::Editor;
  13use fs::{Fs, RemoveOptions};
  14use futures::{
  15    future::{self, Shared},
  16    stream::FuturesUnordered,
  17    FutureExt, StreamExt,
  18};
  19use gpui::{
  20    AppContext, Context as _, EventEmitter, Image, Model, ModelContext, RenderImage, Subscription,
  21    Task, UpdateGlobal, View, WeakView,
  22};
  23
  24use language::{
  25    AnchorRangeExt, Bias, Buffer, BufferSnapshot, LanguageRegistry, OffsetRangeExt, ParseStatus,
  26    Point, ToOffset,
  27};
  28use language_model::{
  29    LanguageModelImage, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
  30    LanguageModelTool, Role,
  31};
  32use open_ai::Model as OpenAiModel;
  33use paths::{context_images_dir, contexts_dir};
  34use project::Project;
  35use schemars::JsonSchema;
  36use serde::{Deserialize, Serialize};
  37use smallvec::SmallVec;
  38use std::{
  39    cmp::{self, Ordering},
  40    collections::hash_map,
  41    fmt::Debug,
  42    iter, mem,
  43    ops::Range,
  44    path::{Path, PathBuf},
  45    sync::Arc,
  46    time::{Duration, Instant},
  47};
  48use telemetry_events::AssistantKind;
  49use ui::{SharedString, WindowContext};
  50use util::{post_inc, ResultExt, TryFutureExt};
  51use uuid::Uuid;
  52use workspace::Workspace;
  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                    },
 119                    version: language::proto::deserialize_version(&insert.version),
 120                })
 121            }
 122            proto::context_operation::Variant::UpdateMessage(update) => Ok(Self::UpdateMessage {
 123                message_id: MessageId(language::proto::deserialize_timestamp(
 124                    update.message_id.context("invalid message id")?,
 125                )),
 126                metadata: MessageMetadata {
 127                    role: Role::from_proto(update.role),
 128                    status: MessageStatus::from_proto(update.status.context("invalid status")?),
 129                    timestamp: language::proto::deserialize_timestamp(
 130                        update.timestamp.context("invalid timestamp")?,
 131                    ),
 132                },
 133                version: language::proto::deserialize_version(&update.version),
 134            }),
 135            proto::context_operation::Variant::UpdateSummary(update) => Ok(Self::UpdateSummary {
 136                summary: ContextSummary {
 137                    text: update.summary,
 138                    done: update.done,
 139                    timestamp: language::proto::deserialize_timestamp(
 140                        update.timestamp.context("invalid timestamp")?,
 141                    ),
 142                },
 143                version: language::proto::deserialize_version(&update.version),
 144            }),
 145            proto::context_operation::Variant::SlashCommandFinished(finished) => {
 146                Ok(Self::SlashCommandFinished {
 147                    id: SlashCommandId(language::proto::deserialize_timestamp(
 148                        finished.id.context("invalid id")?,
 149                    )),
 150                    output_range: language::proto::deserialize_anchor_range(
 151                        finished.output_range.context("invalid range")?,
 152                    )?,
 153                    sections: finished
 154                        .sections
 155                        .into_iter()
 156                        .map(|section| {
 157                            Ok(SlashCommandOutputSection {
 158                                range: language::proto::deserialize_anchor_range(
 159                                    section.range.context("invalid range")?,
 160                                )?,
 161                                icon: section.icon_name.parse()?,
 162                                label: section.label.into(),
 163                            })
 164                        })
 165                        .collect::<Result<Vec<_>>>()?,
 166                    version: language::proto::deserialize_version(&finished.version),
 167                })
 168            }
 169            proto::context_operation::Variant::BufferOperation(op) => Ok(Self::BufferOperation(
 170                language::proto::deserialize_operation(
 171                    op.operation.context("invalid buffer operation")?,
 172                )?,
 173            )),
 174        }
 175    }
 176
 177    pub fn to_proto(&self) -> proto::ContextOperation {
 178        match self {
 179            Self::InsertMessage {
 180                anchor,
 181                metadata,
 182                version,
 183            } => proto::ContextOperation {
 184                variant: Some(proto::context_operation::Variant::InsertMessage(
 185                    proto::context_operation::InsertMessage {
 186                        message: Some(proto::ContextMessage {
 187                            id: Some(language::proto::serialize_timestamp(anchor.id.0)),
 188                            start: Some(language::proto::serialize_anchor(&anchor.start)),
 189                            role: metadata.role.to_proto() as i32,
 190                            status: Some(metadata.status.to_proto()),
 191                        }),
 192                        version: language::proto::serialize_version(version),
 193                    },
 194                )),
 195            },
 196            Self::UpdateMessage {
 197                message_id,
 198                metadata,
 199                version,
 200            } => proto::ContextOperation {
 201                variant: Some(proto::context_operation::Variant::UpdateMessage(
 202                    proto::context_operation::UpdateMessage {
 203                        message_id: Some(language::proto::serialize_timestamp(message_id.0)),
 204                        role: metadata.role.to_proto() as i32,
 205                        status: Some(metadata.status.to_proto()),
 206                        timestamp: Some(language::proto::serialize_timestamp(metadata.timestamp)),
 207                        version: language::proto::serialize_version(version),
 208                    },
 209                )),
 210            },
 211            Self::UpdateSummary { summary, version } => proto::ContextOperation {
 212                variant: Some(proto::context_operation::Variant::UpdateSummary(
 213                    proto::context_operation::UpdateSummary {
 214                        summary: summary.text.clone(),
 215                        done: summary.done,
 216                        timestamp: Some(language::proto::serialize_timestamp(summary.timestamp)),
 217                        version: language::proto::serialize_version(version),
 218                    },
 219                )),
 220            },
 221            Self::SlashCommandFinished {
 222                id,
 223                output_range,
 224                sections,
 225                version,
 226            } => proto::ContextOperation {
 227                variant: Some(proto::context_operation::Variant::SlashCommandFinished(
 228                    proto::context_operation::SlashCommandFinished {
 229                        id: Some(language::proto::serialize_timestamp(id.0)),
 230                        output_range: Some(language::proto::serialize_anchor_range(
 231                            output_range.clone(),
 232                        )),
 233                        sections: sections
 234                            .iter()
 235                            .map(|section| {
 236                                let icon_name: &'static str = section.icon.into();
 237                                proto::SlashCommandOutputSection {
 238                                    range: Some(language::proto::serialize_anchor_range(
 239                                        section.range.clone(),
 240                                    )),
 241                                    icon_name: icon_name.to_string(),
 242                                    label: section.label.to_string(),
 243                                }
 244                            })
 245                            .collect(),
 246                        version: language::proto::serialize_version(version),
 247                    },
 248                )),
 249            },
 250            Self::BufferOperation(operation) => proto::ContextOperation {
 251                variant: Some(proto::context_operation::Variant::BufferOperation(
 252                    proto::context_operation::BufferOperation {
 253                        operation: Some(language::proto::serialize_operation(operation)),
 254                    },
 255                )),
 256            },
 257        }
 258    }
 259
 260    fn timestamp(&self) -> clock::Lamport {
 261        match self {
 262            Self::InsertMessage { anchor, .. } => anchor.id.0,
 263            Self::UpdateMessage { metadata, .. } => metadata.timestamp,
 264            Self::UpdateSummary { summary, .. } => summary.timestamp,
 265            Self::SlashCommandFinished { id, .. } => id.0,
 266            Self::BufferOperation(_) => {
 267                panic!("reading the timestamp of a buffer operation is not supported")
 268            }
 269        }
 270    }
 271
 272    /// Returns the current version of the context operation.
 273    pub fn version(&self) -> &clock::Global {
 274        match self {
 275            Self::InsertMessage { version, .. }
 276            | Self::UpdateMessage { version, .. }
 277            | Self::UpdateSummary { version, .. }
 278            | Self::SlashCommandFinished { version, .. } => version,
 279            Self::BufferOperation(_) => {
 280                panic!("reading the version of a buffer operation is not supported")
 281            }
 282        }
 283    }
 284}
 285
 286#[derive(Debug, Clone)]
 287pub enum ContextEvent {
 288    AssistError(String),
 289    MessagesEdited,
 290    SummaryChanged,
 291    WorkflowStepsRemoved(Vec<Range<language::Anchor>>),
 292    WorkflowStepUpdated(Range<language::Anchor>),
 293    StreamedCompletion,
 294    PendingSlashCommandsUpdated {
 295        removed: Vec<Range<language::Anchor>>,
 296        updated: Vec<PendingSlashCommand>,
 297    },
 298    SlashCommandFinished {
 299        output_range: Range<language::Anchor>,
 300        sections: Vec<SlashCommandOutputSection<language::Anchor>>,
 301        run_commands_in_output: bool,
 302    },
 303    Operation(ContextOperation),
 304}
 305
 306#[derive(Clone, Default, Debug)]
 307pub struct ContextSummary {
 308    pub text: String,
 309    done: bool,
 310    timestamp: clock::Lamport,
 311}
 312
 313#[derive(Clone, Debug, Eq, PartialEq)]
 314pub struct MessageAnchor {
 315    pub id: MessageId,
 316    pub start: language::Anchor,
 317}
 318
 319#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
 320pub struct MessageMetadata {
 321    pub role: Role,
 322    status: MessageStatus,
 323    timestamp: clock::Lamport,
 324}
 325
 326#[derive(Clone, Debug)]
 327pub struct MessageImage {
 328    image_id: u64,
 329    image: Shared<Task<Option<LanguageModelImage>>>,
 330}
 331
 332impl PartialEq for MessageImage {
 333    fn eq(&self, other: &Self) -> bool {
 334        self.image_id == other.image_id
 335    }
 336}
 337
 338impl Eq for MessageImage {}
 339
 340#[derive(Clone, Debug)]
 341pub struct Message {
 342    pub image_offsets: SmallVec<[(usize, MessageImage); 1]>,
 343    pub offset_range: Range<usize>,
 344    pub index_range: Range<usize>,
 345    pub id: MessageId,
 346    pub anchor: language::Anchor,
 347    pub role: Role,
 348    pub status: MessageStatus,
 349}
 350
 351impl Message {
 352    fn to_request_message(&self, buffer: &Buffer) -> LanguageModelRequestMessage {
 353        let mut content = Vec::new();
 354
 355        let mut range_start = self.offset_range.start;
 356        for (image_offset, message_image) in self.image_offsets.iter() {
 357            if *image_offset != range_start {
 358                content.push(
 359                    buffer
 360                        .text_for_range(range_start..*image_offset)
 361                        .collect::<String>()
 362                        .into(),
 363                )
 364            }
 365
 366            if let Some(image) = message_image.image.clone().now_or_never().flatten() {
 367                content.push(language_model::MessageContent::Image(image));
 368            }
 369
 370            range_start = *image_offset;
 371        }
 372        if range_start != self.offset_range.end {
 373            content.push(
 374                buffer
 375                    .text_for_range(range_start..self.offset_range.end)
 376                    .collect::<String>()
 377                    .into(),
 378            )
 379        }
 380
 381        LanguageModelRequestMessage {
 382            role: self.role,
 383            content,
 384        }
 385    }
 386}
 387
 388#[derive(Clone, Debug)]
 389pub struct ImageAnchor {
 390    pub anchor: language::Anchor,
 391    pub image_id: u64,
 392    pub render_image: Arc<RenderImage>,
 393    pub image: Shared<Task<Option<LanguageModelImage>>>,
 394}
 395
 396impl PartialEq for ImageAnchor {
 397    fn eq(&self, other: &Self) -> bool {
 398        self.image_id == other.image_id
 399    }
 400}
 401
 402struct PendingCompletion {
 403    id: usize,
 404    assistant_message_id: MessageId,
 405    _task: Task<()>,
 406}
 407
 408#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
 409pub struct SlashCommandId(clock::Lamport);
 410
 411#[derive(Debug)]
 412pub struct WorkflowStep {
 413    pub tagged_range: Range<language::Anchor>,
 414    pub status: WorkflowStepStatus,
 415}
 416
 417#[derive(Clone, Debug, Eq, PartialEq)]
 418pub struct ResolvedWorkflowStep {
 419    pub title: String,
 420    pub suggestions: HashMap<Model<Buffer>, Vec<WorkflowSuggestionGroup>>,
 421}
 422
 423pub enum WorkflowStepStatus {
 424    Pending(Task<Option<()>>),
 425    Resolved(ResolvedWorkflowStep),
 426    Error(Arc<anyhow::Error>),
 427}
 428
 429impl WorkflowStepStatus {
 430    pub fn into_resolved(&self) -> Option<Result<ResolvedWorkflowStep, Arc<anyhow::Error>>> {
 431        match self {
 432            WorkflowStepStatus::Resolved(resolved) => Some(Ok(resolved.clone())),
 433            WorkflowStepStatus::Error(error) => Some(Err(error.clone())),
 434            WorkflowStepStatus::Pending(_) => None,
 435        }
 436    }
 437}
 438
 439#[derive(Clone, Debug, Eq, PartialEq)]
 440pub struct WorkflowSuggestionGroup {
 441    pub context_range: Range<language::Anchor>,
 442    pub suggestions: Vec<WorkflowSuggestion>,
 443}
 444
 445#[derive(Clone, Debug, Eq, PartialEq)]
 446pub enum WorkflowSuggestion {
 447    Update {
 448        range: Range<language::Anchor>,
 449        description: String,
 450    },
 451    CreateFile {
 452        description: String,
 453    },
 454    InsertSiblingBefore {
 455        position: language::Anchor,
 456        description: String,
 457    },
 458    InsertSiblingAfter {
 459        position: language::Anchor,
 460        description: String,
 461    },
 462    PrependChild {
 463        position: language::Anchor,
 464        description: String,
 465    },
 466    AppendChild {
 467        position: language::Anchor,
 468        description: String,
 469    },
 470    Delete {
 471        range: Range<language::Anchor>,
 472    },
 473}
 474
 475impl WorkflowSuggestion {
 476    pub fn range(&self) -> Range<language::Anchor> {
 477        match self {
 478            WorkflowSuggestion::Update { range, .. } => range.clone(),
 479            WorkflowSuggestion::CreateFile { .. } => language::Anchor::MIN..language::Anchor::MAX,
 480            WorkflowSuggestion::InsertSiblingBefore { position, .. }
 481            | WorkflowSuggestion::InsertSiblingAfter { position, .. }
 482            | WorkflowSuggestion::PrependChild { position, .. }
 483            | WorkflowSuggestion::AppendChild { position, .. } => *position..*position,
 484            WorkflowSuggestion::Delete { range } => range.clone(),
 485        }
 486    }
 487
 488    pub fn description(&self) -> Option<&str> {
 489        match self {
 490            WorkflowSuggestion::Update { description, .. }
 491            | WorkflowSuggestion::CreateFile { description }
 492            | WorkflowSuggestion::InsertSiblingBefore { description, .. }
 493            | WorkflowSuggestion::InsertSiblingAfter { description, .. }
 494            | WorkflowSuggestion::PrependChild { description, .. }
 495            | WorkflowSuggestion::AppendChild { description, .. } => Some(description),
 496            WorkflowSuggestion::Delete { .. } => None,
 497        }
 498    }
 499
 500    fn description_mut(&mut self) -> Option<&mut String> {
 501        match self {
 502            WorkflowSuggestion::Update { description, .. }
 503            | WorkflowSuggestion::CreateFile { description }
 504            | WorkflowSuggestion::InsertSiblingBefore { description, .. }
 505            | WorkflowSuggestion::InsertSiblingAfter { description, .. }
 506            | WorkflowSuggestion::PrependChild { description, .. }
 507            | WorkflowSuggestion::AppendChild { description, .. } => Some(description),
 508            WorkflowSuggestion::Delete { .. } => None,
 509        }
 510    }
 511
 512    fn try_merge(&mut self, other: &Self, buffer: &BufferSnapshot) -> bool {
 513        let range = self.range();
 514        let other_range = other.range();
 515
 516        // Don't merge if we don't contain the other suggestion.
 517        if range.start.cmp(&other_range.start, buffer).is_gt()
 518            || range.end.cmp(&other_range.end, buffer).is_lt()
 519        {
 520            return false;
 521        }
 522
 523        if let Some(description) = self.description_mut() {
 524            if let Some(other_description) = other.description() {
 525                description.push('\n');
 526                description.push_str(other_description);
 527            }
 528        }
 529        true
 530    }
 531
 532    pub fn show(
 533        &self,
 534        editor: &View<Editor>,
 535        excerpt_id: editor::ExcerptId,
 536        workspace: &WeakView<Workspace>,
 537        assistant_panel: &View<AssistantPanel>,
 538        cx: &mut WindowContext,
 539    ) -> Option<InlineAssistId> {
 540        let mut initial_transaction_id = None;
 541        let initial_prompt;
 542        let suggestion_range;
 543        let buffer = editor.read(cx).buffer().clone();
 544        let snapshot = buffer.read(cx).snapshot(cx);
 545
 546        match self {
 547            WorkflowSuggestion::Update { range, description } => {
 548                initial_prompt = description.clone();
 549                suggestion_range = snapshot.anchor_in_excerpt(excerpt_id, range.start)?
 550                    ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?;
 551            }
 552            WorkflowSuggestion::CreateFile { description } => {
 553                initial_prompt = description.clone();
 554                suggestion_range = editor::Anchor::min()..editor::Anchor::min();
 555            }
 556            WorkflowSuggestion::InsertSiblingBefore {
 557                position,
 558                description,
 559            } => {
 560                let position = snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 561                initial_prompt = description.clone();
 562                suggestion_range = buffer.update(cx, |buffer, cx| {
 563                    buffer.start_transaction(cx);
 564                    let line_start = buffer.insert_empty_line(position, true, true, cx);
 565                    initial_transaction_id = buffer.end_transaction(cx);
 566                    buffer.refresh_preview(cx);
 567
 568                    let line_start = buffer.read(cx).anchor_before(line_start);
 569                    line_start..line_start
 570                });
 571            }
 572            WorkflowSuggestion::InsertSiblingAfter {
 573                position,
 574                description,
 575            } => {
 576                let position = snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 577                initial_prompt = description.clone();
 578                suggestion_range = buffer.update(cx, |buffer, cx| {
 579                    buffer.start_transaction(cx);
 580                    let line_start = buffer.insert_empty_line(position, true, true, cx);
 581                    initial_transaction_id = buffer.end_transaction(cx);
 582                    buffer.refresh_preview(cx);
 583
 584                    let line_start = buffer.read(cx).anchor_before(line_start);
 585                    line_start..line_start
 586                });
 587            }
 588            WorkflowSuggestion::PrependChild {
 589                position,
 590                description,
 591            } => {
 592                let position = snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 593                initial_prompt = description.clone();
 594                suggestion_range = buffer.update(cx, |buffer, cx| {
 595                    buffer.start_transaction(cx);
 596                    let line_start = buffer.insert_empty_line(position, false, true, cx);
 597                    initial_transaction_id = buffer.end_transaction(cx);
 598                    buffer.refresh_preview(cx);
 599
 600                    let line_start = buffer.read(cx).anchor_before(line_start);
 601                    line_start..line_start
 602                });
 603            }
 604            WorkflowSuggestion::AppendChild {
 605                position,
 606                description,
 607            } => {
 608                let position = snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 609                initial_prompt = description.clone();
 610                suggestion_range = buffer.update(cx, |buffer, cx| {
 611                    buffer.start_transaction(cx);
 612                    let line_start = buffer.insert_empty_line(position, true, false, cx);
 613                    initial_transaction_id = buffer.end_transaction(cx);
 614                    buffer.refresh_preview(cx);
 615
 616                    let line_start = buffer.read(cx).anchor_before(line_start);
 617                    line_start..line_start
 618                });
 619            }
 620            WorkflowSuggestion::Delete { range } => {
 621                initial_prompt = "Delete".to_string();
 622                suggestion_range = snapshot.anchor_in_excerpt(excerpt_id, range.start)?
 623                    ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?;
 624            }
 625        }
 626
 627        InlineAssistant::update_global(cx, |inline_assistant, cx| {
 628            Some(inline_assistant.suggest_assist(
 629                editor,
 630                suggestion_range,
 631                initial_prompt,
 632                initial_transaction_id,
 633                Some(workspace.clone()),
 634                Some(assistant_panel),
 635                cx,
 636            ))
 637        })
 638    }
 639}
 640
 641impl Debug for WorkflowStepStatus {
 642    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 643        match self {
 644            WorkflowStepStatus::Pending(_) => write!(f, "WorkflowStepStatus::Pending"),
 645            WorkflowStepStatus::Resolved(ResolvedWorkflowStep { title, suggestions }) => f
 646                .debug_struct("WorkflowStepStatus::Resolved")
 647                .field("title", title)
 648                .field("suggestions", suggestions)
 649                .finish(),
 650            WorkflowStepStatus::Error(error) => f
 651                .debug_tuple("WorkflowStepStatus::Error")
 652                .field(error)
 653                .finish(),
 654        }
 655    }
 656}
 657
 658pub struct Context {
 659    id: ContextId,
 660    timestamp: clock::Lamport,
 661    version: clock::Global,
 662    pending_ops: Vec<ContextOperation>,
 663    operations: Vec<ContextOperation>,
 664    buffer: Model<Buffer>,
 665    pending_slash_commands: Vec<PendingSlashCommand>,
 666    edits_since_last_slash_command_parse: language::Subscription,
 667    finished_slash_commands: HashSet<SlashCommandId>,
 668    slash_command_output_sections: Vec<SlashCommandOutputSection<language::Anchor>>,
 669    message_anchors: Vec<MessageAnchor>,
 670    images: HashMap<u64, (Arc<RenderImage>, Shared<Task<Option<LanguageModelImage>>>)>,
 671    image_anchors: Vec<ImageAnchor>,
 672    messages_metadata: HashMap<MessageId, MessageMetadata>,
 673    summary: Option<ContextSummary>,
 674    pending_summary: Task<Option<()>>,
 675    completion_count: usize,
 676    pending_completions: Vec<PendingCompletion>,
 677    token_count: Option<usize>,
 678    pending_token_count: Task<Option<()>>,
 679    pending_save: Task<Result<()>>,
 680    path: Option<PathBuf>,
 681    _subscriptions: Vec<Subscription>,
 682    telemetry: Option<Arc<Telemetry>>,
 683    language_registry: Arc<LanguageRegistry>,
 684    workflow_steps: Vec<WorkflowStep>,
 685    edits_since_last_workflow_step_prune: language::Subscription,
 686    project: Option<Model<Project>>,
 687    prompt_builder: Arc<PromptBuilder>,
 688}
 689
 690impl EventEmitter<ContextEvent> for Context {}
 691
 692impl Context {
 693    pub fn local(
 694        language_registry: Arc<LanguageRegistry>,
 695        project: Option<Model<Project>>,
 696        telemetry: Option<Arc<Telemetry>>,
 697        prompt_builder: Arc<PromptBuilder>,
 698        cx: &mut ModelContext<Self>,
 699    ) -> Self {
 700        Self::new(
 701            ContextId::new(),
 702            ReplicaId::default(),
 703            language::Capability::ReadWrite,
 704            language_registry,
 705            prompt_builder,
 706            project,
 707            telemetry,
 708            cx,
 709        )
 710    }
 711
 712    #[allow(clippy::too_many_arguments)]
 713    pub fn new(
 714        id: ContextId,
 715        replica_id: ReplicaId,
 716        capability: language::Capability,
 717        language_registry: Arc<LanguageRegistry>,
 718        prompt_builder: Arc<PromptBuilder>,
 719        project: Option<Model<Project>>,
 720        telemetry: Option<Arc<Telemetry>>,
 721        cx: &mut ModelContext<Self>,
 722    ) -> Self {
 723        let buffer = cx.new_model(|_cx| {
 724            let mut buffer = Buffer::remote(
 725                language::BufferId::new(1).unwrap(),
 726                replica_id,
 727                capability,
 728                "",
 729            );
 730            buffer.set_language_registry(language_registry.clone());
 731            buffer
 732        });
 733        let edits_since_last_slash_command_parse =
 734            buffer.update(cx, |buffer, _| buffer.subscribe());
 735        let edits_since_last_workflow_step_prune =
 736            buffer.update(cx, |buffer, _| buffer.subscribe());
 737        let mut this = Self {
 738            id,
 739            timestamp: clock::Lamport::new(replica_id),
 740            version: clock::Global::new(),
 741            pending_ops: Vec::new(),
 742            operations: Vec::new(),
 743            message_anchors: Default::default(),
 744            image_anchors: Default::default(),
 745            images: Default::default(),
 746            messages_metadata: Default::default(),
 747            pending_slash_commands: Vec::new(),
 748            finished_slash_commands: HashSet::default(),
 749            slash_command_output_sections: Vec::new(),
 750            edits_since_last_slash_command_parse,
 751            summary: None,
 752            pending_summary: Task::ready(None),
 753            completion_count: Default::default(),
 754            pending_completions: Default::default(),
 755            token_count: None,
 756            pending_token_count: Task::ready(None),
 757            _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
 758            pending_save: Task::ready(Ok(())),
 759            path: None,
 760            buffer,
 761            telemetry,
 762            project,
 763            language_registry,
 764            workflow_steps: Vec::new(),
 765            edits_since_last_workflow_step_prune,
 766            prompt_builder,
 767        };
 768
 769        let first_message_id = MessageId(clock::Lamport {
 770            replica_id: 0,
 771            value: 0,
 772        });
 773        let message = MessageAnchor {
 774            id: first_message_id,
 775            start: language::Anchor::MIN,
 776        };
 777        this.messages_metadata.insert(
 778            first_message_id,
 779            MessageMetadata {
 780                role: Role::User,
 781                status: MessageStatus::Done,
 782                timestamp: first_message_id.0,
 783            },
 784        );
 785        this.message_anchors.push(message);
 786
 787        this.set_language(cx);
 788        this.count_remaining_tokens(cx);
 789        this
 790    }
 791
 792    fn serialize(&self, cx: &AppContext) -> SavedContext {
 793        let buffer = self.buffer.read(cx);
 794        SavedContext {
 795            id: Some(self.id.clone()),
 796            zed: "context".into(),
 797            version: SavedContext::VERSION.into(),
 798            text: buffer.text(),
 799            messages: self
 800                .messages(cx)
 801                .map(|message| SavedMessage {
 802                    id: message.id,
 803                    start: message.offset_range.start,
 804                    metadata: self.messages_metadata[&message.id].clone(),
 805                    image_offsets: message
 806                        .image_offsets
 807                        .iter()
 808                        .map(|image_offset| (image_offset.0, image_offset.1.image_id))
 809                        .collect(),
 810                })
 811                .collect(),
 812            summary: self
 813                .summary
 814                .as_ref()
 815                .map(|summary| summary.text.clone())
 816                .unwrap_or_default(),
 817            slash_command_output_sections: self
 818                .slash_command_output_sections
 819                .iter()
 820                .filter_map(|section| {
 821                    let range = section.range.to_offset(buffer);
 822                    if section.range.start.is_valid(buffer) && !range.is_empty() {
 823                        Some(assistant_slash_command::SlashCommandOutputSection {
 824                            range,
 825                            icon: section.icon,
 826                            label: section.label.clone(),
 827                        })
 828                    } else {
 829                        None
 830                    }
 831                })
 832                .collect(),
 833        }
 834    }
 835
 836    #[allow(clippy::too_many_arguments)]
 837    pub fn deserialize(
 838        saved_context: SavedContext,
 839        path: PathBuf,
 840        language_registry: Arc<LanguageRegistry>,
 841        prompt_builder: Arc<PromptBuilder>,
 842        project: Option<Model<Project>>,
 843        telemetry: Option<Arc<Telemetry>>,
 844        cx: &mut ModelContext<Self>,
 845    ) -> Self {
 846        let id = saved_context.id.clone().unwrap_or_else(|| ContextId::new());
 847        let mut this = Self::new(
 848            id,
 849            ReplicaId::default(),
 850            language::Capability::ReadWrite,
 851            language_registry,
 852            prompt_builder,
 853            project,
 854            telemetry,
 855            cx,
 856        );
 857        this.path = Some(path);
 858        this.buffer.update(cx, |buffer, cx| {
 859            buffer.set_text(saved_context.text.as_str(), cx)
 860        });
 861        let operations = saved_context.into_ops(&this.buffer, cx);
 862        this.apply_ops(operations, cx).unwrap();
 863        this
 864    }
 865
 866    pub fn id(&self) -> &ContextId {
 867        &self.id
 868    }
 869
 870    pub fn replica_id(&self) -> ReplicaId {
 871        self.timestamp.replica_id
 872    }
 873
 874    pub fn version(&self, cx: &AppContext) -> ContextVersion {
 875        ContextVersion {
 876            context: self.version.clone(),
 877            buffer: self.buffer.read(cx).version(),
 878        }
 879    }
 880
 881    pub fn set_capability(
 882        &mut self,
 883        capability: language::Capability,
 884        cx: &mut ModelContext<Self>,
 885    ) {
 886        self.buffer
 887            .update(cx, |buffer, cx| buffer.set_capability(capability, cx));
 888    }
 889
 890    fn next_timestamp(&mut self) -> clock::Lamport {
 891        let timestamp = self.timestamp.tick();
 892        self.version.observe(timestamp);
 893        timestamp
 894    }
 895
 896    pub fn serialize_ops(
 897        &self,
 898        since: &ContextVersion,
 899        cx: &AppContext,
 900    ) -> Task<Vec<proto::ContextOperation>> {
 901        let buffer_ops = self
 902            .buffer
 903            .read(cx)
 904            .serialize_ops(Some(since.buffer.clone()), cx);
 905
 906        let mut context_ops = self
 907            .operations
 908            .iter()
 909            .filter(|op| !since.context.observed(op.timestamp()))
 910            .cloned()
 911            .collect::<Vec<_>>();
 912        context_ops.extend(self.pending_ops.iter().cloned());
 913
 914        cx.background_executor().spawn(async move {
 915            let buffer_ops = buffer_ops.await;
 916            context_ops.sort_unstable_by_key(|op| op.timestamp());
 917            buffer_ops
 918                .into_iter()
 919                .map(|op| proto::ContextOperation {
 920                    variant: Some(proto::context_operation::Variant::BufferOperation(
 921                        proto::context_operation::BufferOperation {
 922                            operation: Some(op),
 923                        },
 924                    )),
 925                })
 926                .chain(context_ops.into_iter().map(|op| op.to_proto()))
 927                .collect()
 928        })
 929    }
 930
 931    pub fn apply_ops(
 932        &mut self,
 933        ops: impl IntoIterator<Item = ContextOperation>,
 934        cx: &mut ModelContext<Self>,
 935    ) -> Result<()> {
 936        let mut buffer_ops = Vec::new();
 937        for op in ops {
 938            match op {
 939                ContextOperation::BufferOperation(buffer_op) => buffer_ops.push(buffer_op),
 940                op @ _ => self.pending_ops.push(op),
 941            }
 942        }
 943        self.buffer
 944            .update(cx, |buffer, cx| buffer.apply_ops(buffer_ops, cx))?;
 945        self.flush_ops(cx);
 946
 947        Ok(())
 948    }
 949
 950    fn flush_ops(&mut self, cx: &mut ModelContext<Context>) {
 951        let mut messages_changed = false;
 952        let mut summary_changed = false;
 953
 954        self.pending_ops.sort_unstable_by_key(|op| op.timestamp());
 955        for op in mem::take(&mut self.pending_ops) {
 956            if !self.can_apply_op(&op, cx) {
 957                self.pending_ops.push(op);
 958                continue;
 959            }
 960
 961            let timestamp = op.timestamp();
 962            match op.clone() {
 963                ContextOperation::InsertMessage {
 964                    anchor, metadata, ..
 965                } => {
 966                    if self.messages_metadata.contains_key(&anchor.id) {
 967                        // We already applied this operation.
 968                    } else {
 969                        self.insert_message(anchor, metadata, cx);
 970                        messages_changed = true;
 971                    }
 972                }
 973                ContextOperation::UpdateMessage {
 974                    message_id,
 975                    metadata: new_metadata,
 976                    ..
 977                } => {
 978                    let metadata = self.messages_metadata.get_mut(&message_id).unwrap();
 979                    if new_metadata.timestamp > metadata.timestamp {
 980                        *metadata = new_metadata;
 981                        messages_changed = true;
 982                    }
 983                }
 984                ContextOperation::UpdateSummary {
 985                    summary: new_summary,
 986                    ..
 987                } => {
 988                    if self
 989                        .summary
 990                        .as_ref()
 991                        .map_or(true, |summary| new_summary.timestamp > summary.timestamp)
 992                    {
 993                        self.summary = Some(new_summary);
 994                        summary_changed = true;
 995                    }
 996                }
 997                ContextOperation::SlashCommandFinished {
 998                    id,
 999                    output_range,
1000                    sections,
1001                    ..
1002                } => {
1003                    if self.finished_slash_commands.insert(id) {
1004                        let buffer = self.buffer.read(cx);
1005                        self.slash_command_output_sections
1006                            .extend(sections.iter().cloned());
1007                        self.slash_command_output_sections
1008                            .sort_by(|a, b| a.range.cmp(&b.range, buffer));
1009                        cx.emit(ContextEvent::SlashCommandFinished {
1010                            output_range,
1011                            sections,
1012                            run_commands_in_output: false,
1013                        });
1014                    }
1015                }
1016                ContextOperation::BufferOperation(_) => unreachable!(),
1017            }
1018
1019            self.version.observe(timestamp);
1020            self.timestamp.observe(timestamp);
1021            self.operations.push(op);
1022        }
1023
1024        if messages_changed {
1025            cx.emit(ContextEvent::MessagesEdited);
1026            cx.notify();
1027        }
1028
1029        if summary_changed {
1030            cx.emit(ContextEvent::SummaryChanged);
1031            cx.notify();
1032        }
1033    }
1034
1035    fn can_apply_op(&self, op: &ContextOperation, cx: &AppContext) -> bool {
1036        if !self.version.observed_all(op.version()) {
1037            return false;
1038        }
1039
1040        match op {
1041            ContextOperation::InsertMessage { anchor, .. } => self
1042                .buffer
1043                .read(cx)
1044                .version
1045                .observed(anchor.start.timestamp),
1046            ContextOperation::UpdateMessage { message_id, .. } => {
1047                self.messages_metadata.contains_key(message_id)
1048            }
1049            ContextOperation::UpdateSummary { .. } => true,
1050            ContextOperation::SlashCommandFinished {
1051                output_range,
1052                sections,
1053                ..
1054            } => {
1055                let version = &self.buffer.read(cx).version;
1056                sections
1057                    .iter()
1058                    .map(|section| &section.range)
1059                    .chain([output_range])
1060                    .all(|range| {
1061                        let observed_start = range.start == language::Anchor::MIN
1062                            || range.start == language::Anchor::MAX
1063                            || version.observed(range.start.timestamp);
1064                        let observed_end = range.end == language::Anchor::MIN
1065                            || range.end == language::Anchor::MAX
1066                            || version.observed(range.end.timestamp);
1067                        observed_start && observed_end
1068                    })
1069            }
1070            ContextOperation::BufferOperation(_) => {
1071                panic!("buffer operations should always be applied")
1072            }
1073        }
1074    }
1075
1076    fn push_op(&mut self, op: ContextOperation, cx: &mut ModelContext<Self>) {
1077        self.operations.push(op.clone());
1078        cx.emit(ContextEvent::Operation(op));
1079    }
1080
1081    pub fn buffer(&self) -> &Model<Buffer> {
1082        &self.buffer
1083    }
1084
1085    pub fn path(&self) -> Option<&Path> {
1086        self.path.as_deref()
1087    }
1088
1089    pub fn summary(&self) -> Option<&ContextSummary> {
1090        self.summary.as_ref()
1091    }
1092
1093    pub fn workflow_steps(&self) -> &[WorkflowStep] {
1094        &self.workflow_steps
1095    }
1096
1097    pub fn workflow_step_for_range(&self, range: Range<language::Anchor>) -> Option<&WorkflowStep> {
1098        self.workflow_steps
1099            .iter()
1100            .find(|step| step.tagged_range == range)
1101    }
1102
1103    pub fn pending_slash_commands(&self) -> &[PendingSlashCommand] {
1104        &self.pending_slash_commands
1105    }
1106
1107    pub fn slash_command_output_sections(&self) -> &[SlashCommandOutputSection<language::Anchor>] {
1108        &self.slash_command_output_sections
1109    }
1110
1111    fn set_language(&mut self, cx: &mut ModelContext<Self>) {
1112        let markdown = self.language_registry.language_for_name("Markdown");
1113        cx.spawn(|this, mut cx| async move {
1114            let markdown = markdown.await?;
1115            this.update(&mut cx, |this, cx| {
1116                this.buffer
1117                    .update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx));
1118            })
1119        })
1120        .detach_and_log_err(cx);
1121    }
1122
1123    fn handle_buffer_event(
1124        &mut self,
1125        _: Model<Buffer>,
1126        event: &language::Event,
1127        cx: &mut ModelContext<Self>,
1128    ) {
1129        match event {
1130            language::Event::Operation(operation) => cx.emit(ContextEvent::Operation(
1131                ContextOperation::BufferOperation(operation.clone()),
1132            )),
1133            language::Event::Edited => {
1134                self.count_remaining_tokens(cx);
1135                self.reparse_slash_commands(cx);
1136                // Use `inclusive = true` to invalidate a step when an edit occurs
1137                // at the start/end of a parsed step.
1138                self.prune_invalid_workflow_steps(true, cx);
1139                cx.emit(ContextEvent::MessagesEdited);
1140            }
1141            _ => {}
1142        }
1143    }
1144
1145    pub(crate) fn token_count(&self) -> Option<usize> {
1146        self.token_count
1147    }
1148
1149    pub(crate) fn count_remaining_tokens(&mut self, cx: &mut ModelContext<Self>) {
1150        let request = self.to_completion_request(cx);
1151        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1152            return;
1153        };
1154        self.pending_token_count = cx.spawn(|this, mut cx| {
1155            async move {
1156                cx.background_executor()
1157                    .timer(Duration::from_millis(200))
1158                    .await;
1159
1160                let token_count = cx.update(|cx| model.count_tokens(request, cx))?.await?;
1161                this.update(&mut cx, |this, cx| {
1162                    this.token_count = Some(token_count);
1163                    cx.notify()
1164                })
1165            }
1166            .log_err()
1167        });
1168    }
1169
1170    pub fn reparse_slash_commands(&mut self, cx: &mut ModelContext<Self>) {
1171        let buffer = self.buffer.read(cx);
1172        let mut row_ranges = self
1173            .edits_since_last_slash_command_parse
1174            .consume()
1175            .into_iter()
1176            .map(|edit| {
1177                let start_row = buffer.offset_to_point(edit.new.start).row;
1178                let end_row = buffer.offset_to_point(edit.new.end).row + 1;
1179                start_row..end_row
1180            })
1181            .peekable();
1182
1183        let mut removed = Vec::new();
1184        let mut updated = Vec::new();
1185        while let Some(mut row_range) = row_ranges.next() {
1186            while let Some(next_row_range) = row_ranges.peek() {
1187                if row_range.end >= next_row_range.start {
1188                    row_range.end = next_row_range.end;
1189                    row_ranges.next();
1190                } else {
1191                    break;
1192                }
1193            }
1194
1195            let start = buffer.anchor_before(Point::new(row_range.start, 0));
1196            let end = buffer.anchor_after(Point::new(
1197                row_range.end - 1,
1198                buffer.line_len(row_range.end - 1),
1199            ));
1200
1201            let old_range = self.pending_command_indices_for_range(start..end, cx);
1202
1203            let mut new_commands = Vec::new();
1204            let mut lines = buffer.text_for_range(start..end).lines();
1205            let mut offset = lines.offset();
1206            while let Some(line) = lines.next() {
1207                if let Some(command_line) = SlashCommandLine::parse(line) {
1208                    let name = &line[command_line.name.clone()];
1209                    let arguments = command_line
1210                        .arguments
1211                        .iter()
1212                        .filter_map(|argument_range| {
1213                            if argument_range.is_empty() {
1214                                None
1215                            } else {
1216                                line.get(argument_range.clone())
1217                            }
1218                        })
1219                        .map(ToOwned::to_owned)
1220                        .collect::<SmallVec<_>>();
1221                    if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1222                        if !command.requires_argument() || !arguments.is_empty() {
1223                            let start_ix = offset + command_line.name.start - 1;
1224                            let end_ix = offset
1225                                + command_line
1226                                    .arguments
1227                                    .last()
1228                                    .map_or(command_line.name.end, |argument| argument.end);
1229                            let source_range =
1230                                buffer.anchor_after(start_ix)..buffer.anchor_after(end_ix);
1231                            let pending_command = PendingSlashCommand {
1232                                name: name.to_string(),
1233                                arguments,
1234                                source_range,
1235                                status: PendingSlashCommandStatus::Idle,
1236                            };
1237                            updated.push(pending_command.clone());
1238                            new_commands.push(pending_command);
1239                        }
1240                    }
1241                }
1242
1243                offset = lines.offset();
1244            }
1245
1246            let removed_commands = self.pending_slash_commands.splice(old_range, new_commands);
1247            removed.extend(removed_commands.map(|command| command.source_range));
1248        }
1249
1250        if !updated.is_empty() || !removed.is_empty() {
1251            cx.emit(ContextEvent::PendingSlashCommandsUpdated { removed, updated });
1252        }
1253    }
1254
1255    fn prune_invalid_workflow_steps(&mut self, inclusive: bool, cx: &mut ModelContext<Self>) {
1256        let mut removed = Vec::new();
1257
1258        for edit_range in self.edits_since_last_workflow_step_prune.consume() {
1259            let intersecting_range = self.find_intersecting_steps(edit_range.new, inclusive, cx);
1260            removed.extend(
1261                self.workflow_steps
1262                    .drain(intersecting_range)
1263                    .map(|step| step.tagged_range),
1264            );
1265        }
1266
1267        if !removed.is_empty() {
1268            cx.emit(ContextEvent::WorkflowStepsRemoved(removed));
1269            cx.notify();
1270        }
1271    }
1272
1273    fn find_intersecting_steps(
1274        &self,
1275        range: Range<usize>,
1276        inclusive: bool,
1277        cx: &AppContext,
1278    ) -> Range<usize> {
1279        let buffer = self.buffer.read(cx);
1280        let start_ix = match self.workflow_steps.binary_search_by(|probe| {
1281            probe
1282                .tagged_range
1283                .end
1284                .to_offset(buffer)
1285                .cmp(&range.start)
1286                .then(if inclusive {
1287                    Ordering::Greater
1288                } else {
1289                    Ordering::Less
1290                })
1291        }) {
1292            Ok(ix) | Err(ix) => ix,
1293        };
1294        let end_ix = match self.workflow_steps.binary_search_by(|probe| {
1295            probe
1296                .tagged_range
1297                .start
1298                .to_offset(buffer)
1299                .cmp(&range.end)
1300                .then(if inclusive {
1301                    Ordering::Less
1302                } else {
1303                    Ordering::Greater
1304                })
1305        }) {
1306            Ok(ix) | Err(ix) => ix,
1307        };
1308        start_ix..end_ix
1309    }
1310
1311    fn parse_workflow_steps_in_range(
1312        &mut self,
1313        range: Range<usize>,
1314        project: Model<Project>,
1315        cx: &mut ModelContext<Self>,
1316    ) {
1317        let mut new_edit_steps = Vec::new();
1318        let mut edits = Vec::new();
1319
1320        let buffer = self.buffer.read(cx).snapshot();
1321        let mut message_lines = buffer.as_rope().chunks_in_range(range).lines();
1322        let mut in_step = false;
1323        let mut step_open_tag_start_ix = 0;
1324        let mut line_start_offset = message_lines.offset();
1325
1326        while let Some(line) = message_lines.next() {
1327            if let Some(step_start_index) = line.find("<step>") {
1328                if !in_step {
1329                    in_step = true;
1330                    step_open_tag_start_ix = line_start_offset + step_start_index;
1331                }
1332            }
1333
1334            if let Some(step_end_index) = line.find("</step>") {
1335                if in_step {
1336                    let mut step_open_tag_end_ix = step_open_tag_start_ix + "<step>".len();
1337                    if buffer.chars_at(step_open_tag_end_ix).next() == Some('\n') {
1338                        step_open_tag_end_ix += 1;
1339                    }
1340                    let mut step_end_tag_start_ix = line_start_offset + step_end_index;
1341                    let step_end_tag_end_ix = step_end_tag_start_ix + "</step>".len();
1342                    if buffer.reversed_chars_at(step_end_tag_start_ix).next() == Some('\n') {
1343                        step_end_tag_start_ix -= 1;
1344                    }
1345                    edits.push((step_open_tag_start_ix..step_open_tag_end_ix, ""));
1346                    edits.push((step_end_tag_start_ix..step_end_tag_end_ix, ""));
1347                    let tagged_range = buffer.anchor_after(step_open_tag_end_ix)
1348                        ..buffer.anchor_before(step_end_tag_start_ix);
1349
1350                    // Check if a step with the same range already exists
1351                    let existing_step_index = self
1352                        .workflow_steps
1353                        .binary_search_by(|probe| probe.tagged_range.cmp(&tagged_range, &buffer));
1354
1355                    if let Err(ix) = existing_step_index {
1356                        new_edit_steps.push((
1357                            ix,
1358                            WorkflowStep {
1359                                tagged_range,
1360                                status: WorkflowStepStatus::Pending(Task::ready(None)),
1361                            },
1362                        ));
1363                    }
1364
1365                    in_step = false;
1366                }
1367            }
1368
1369            line_start_offset = message_lines.offset();
1370        }
1371
1372        let mut updated = Vec::new();
1373        for (index, step) in new_edit_steps.into_iter().rev() {
1374            let step_range = step.tagged_range.clone();
1375            updated.push(step_range.clone());
1376            self.workflow_steps.insert(index, step);
1377            self.resolve_workflow_step(step_range, project.clone(), cx);
1378        }
1379
1380        // Delete <step> tags, making sure we don't accidentally invalidate
1381        // the step we just parsed.
1382        self.buffer
1383            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
1384        self.edits_since_last_workflow_step_prune.consume();
1385    }
1386
1387    pub fn resolve_workflow_step(
1388        &mut self,
1389        tagged_range: Range<language::Anchor>,
1390        project: Model<Project>,
1391        cx: &mut ModelContext<Self>,
1392    ) {
1393        let Ok(step_index) = self
1394            .workflow_steps
1395            .binary_search_by(|step| step.tagged_range.cmp(&tagged_range, self.buffer.read(cx)))
1396        else {
1397            return;
1398        };
1399
1400        let mut request = self.to_completion_request(cx);
1401        let Some(edit_step) = self.workflow_steps.get_mut(step_index) else {
1402            return;
1403        };
1404
1405        if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
1406            let step_text = self
1407                .buffer
1408                .read(cx)
1409                .text_for_range(tagged_range.clone())
1410                .collect::<String>();
1411
1412            let tagged_range = tagged_range.clone();
1413            edit_step.status = WorkflowStepStatus::Pending(cx.spawn(|this, mut cx| {
1414                async move {
1415                    let result = async {
1416                        let mut prompt = this.update(&mut cx, |this, _| {
1417                            this.prompt_builder.generate_step_resolution_prompt()
1418                        })??;
1419                        prompt.push_str(&step_text);
1420
1421                        request.messages.push(LanguageModelRequestMessage {
1422                            role: Role::User,
1423                            content: vec![prompt.into()],
1424                        });
1425
1426                        // Invoke the model to get its edit suggestions for this workflow step.
1427                        let resolution = model
1428                            .use_tool::<tool::WorkflowStepResolution>(request, &cx)
1429                            .await?;
1430
1431                        // Translate the parsed suggestions to our internal types, which anchor the suggestions to locations in the code.
1432                        let suggestion_tasks: Vec<_> = resolution
1433                            .suggestions
1434                            .iter()
1435                            .map(|suggestion| suggestion.resolve(project.clone(), cx.clone()))
1436                            .collect();
1437
1438                        // Expand the context ranges of each suggestion and group suggestions with overlapping context ranges.
1439                        let suggestions = future::join_all(suggestion_tasks)
1440                            .await
1441                            .into_iter()
1442                            .filter_map(|task| task.log_err())
1443                            .collect::<Vec<_>>();
1444
1445                        let mut suggestions_by_buffer = HashMap::default();
1446                        for (buffer, suggestion) in suggestions {
1447                            suggestions_by_buffer
1448                                .entry(buffer)
1449                                .or_insert_with(Vec::new)
1450                                .push(suggestion);
1451                        }
1452
1453                        let mut suggestion_groups_by_buffer = HashMap::default();
1454                        for (buffer, mut suggestions) in suggestions_by_buffer {
1455                            let mut suggestion_groups = Vec::<WorkflowSuggestionGroup>::new();
1456                            let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
1457                            // Sort suggestions by their range so that earlier, larger ranges come first
1458                            suggestions.sort_by(|a, b| a.range().cmp(&b.range(), &snapshot));
1459
1460                            // Merge overlapping suggestions
1461                            suggestions.dedup_by(|a, b| b.try_merge(&a, &snapshot));
1462
1463                            // Create context ranges for each suggestion
1464                            for suggestion in suggestions {
1465                                let context_range = {
1466                                    let suggestion_point_range =
1467                                        suggestion.range().to_point(&snapshot);
1468                                    let start_row =
1469                                        suggestion_point_range.start.row.saturating_sub(5);
1470                                    let end_row = cmp::min(
1471                                        suggestion_point_range.end.row + 5,
1472                                        snapshot.max_point().row,
1473                                    );
1474                                    let start = snapshot.anchor_before(Point::new(start_row, 0));
1475                                    let end = snapshot.anchor_after(Point::new(
1476                                        end_row,
1477                                        snapshot.line_len(end_row),
1478                                    ));
1479                                    start..end
1480                                };
1481
1482                                if let Some(last_group) = suggestion_groups.last_mut() {
1483                                    if last_group
1484                                        .context_range
1485                                        .end
1486                                        .cmp(&context_range.start, &snapshot)
1487                                        .is_ge()
1488                                    {
1489                                        // Merge with the previous group if context ranges overlap
1490                                        last_group.context_range.end = context_range.end;
1491                                        last_group.suggestions.push(suggestion);
1492                                    } else {
1493                                        // Create a new group
1494                                        suggestion_groups.push(WorkflowSuggestionGroup {
1495                                            context_range,
1496                                            suggestions: vec![suggestion],
1497                                        });
1498                                    }
1499                                } else {
1500                                    // Create the first group
1501                                    suggestion_groups.push(WorkflowSuggestionGroup {
1502                                        context_range,
1503                                        suggestions: vec![suggestion],
1504                                    });
1505                                }
1506                            }
1507
1508                            suggestion_groups_by_buffer.insert(buffer, suggestion_groups);
1509                        }
1510
1511                        Ok((resolution.step_title, suggestion_groups_by_buffer))
1512                    };
1513
1514                    let result = result.await;
1515                    this.update(&mut cx, |this, cx| {
1516                        let step_index = this
1517                            .workflow_steps
1518                            .binary_search_by(|step| {
1519                                step.tagged_range.cmp(&tagged_range, this.buffer.read(cx))
1520                            })
1521                            .map_err(|_| anyhow!("edit step not found"))?;
1522                        if let Some(edit_step) = this.workflow_steps.get_mut(step_index) {
1523                            edit_step.status = match result {
1524                                Ok((title, suggestions)) => {
1525                                    WorkflowStepStatus::Resolved(ResolvedWorkflowStep {
1526                                        title,
1527                                        suggestions,
1528                                    })
1529                                }
1530                                Err(error) => WorkflowStepStatus::Error(Arc::new(error)),
1531                            };
1532                            cx.emit(ContextEvent::WorkflowStepUpdated(tagged_range));
1533                            cx.notify();
1534                        }
1535                        anyhow::Ok(())
1536                    })?
1537                }
1538                .log_err()
1539            }));
1540        } else {
1541            edit_step.status = WorkflowStepStatus::Error(Arc::new(anyhow!("no active model")));
1542        }
1543
1544        cx.emit(ContextEvent::WorkflowStepUpdated(tagged_range));
1545        cx.notify();
1546    }
1547
1548    pub fn pending_command_for_position(
1549        &mut self,
1550        position: language::Anchor,
1551        cx: &mut ModelContext<Self>,
1552    ) -> Option<&mut PendingSlashCommand> {
1553        let buffer = self.buffer.read(cx);
1554        match self
1555            .pending_slash_commands
1556            .binary_search_by(|probe| probe.source_range.end.cmp(&position, buffer))
1557        {
1558            Ok(ix) => Some(&mut self.pending_slash_commands[ix]),
1559            Err(ix) => {
1560                let cmd = self.pending_slash_commands.get_mut(ix)?;
1561                if position.cmp(&cmd.source_range.start, buffer).is_ge()
1562                    && position.cmp(&cmd.source_range.end, buffer).is_le()
1563                {
1564                    Some(cmd)
1565                } else {
1566                    None
1567                }
1568            }
1569        }
1570    }
1571
1572    pub fn pending_commands_for_range(
1573        &self,
1574        range: Range<language::Anchor>,
1575        cx: &AppContext,
1576    ) -> &[PendingSlashCommand] {
1577        let range = self.pending_command_indices_for_range(range, cx);
1578        &self.pending_slash_commands[range]
1579    }
1580
1581    fn pending_command_indices_for_range(
1582        &self,
1583        range: Range<language::Anchor>,
1584        cx: &AppContext,
1585    ) -> Range<usize> {
1586        let buffer = self.buffer.read(cx);
1587        let start_ix = match self
1588            .pending_slash_commands
1589            .binary_search_by(|probe| probe.source_range.end.cmp(&range.start, &buffer))
1590        {
1591            Ok(ix) | Err(ix) => ix,
1592        };
1593        let end_ix = match self
1594            .pending_slash_commands
1595            .binary_search_by(|probe| probe.source_range.start.cmp(&range.end, &buffer))
1596        {
1597            Ok(ix) => ix + 1,
1598            Err(ix) => ix,
1599        };
1600        start_ix..end_ix
1601    }
1602
1603    pub fn insert_command_output(
1604        &mut self,
1605        command_range: Range<language::Anchor>,
1606        output: Task<Result<SlashCommandOutput>>,
1607        insert_trailing_newline: bool,
1608        cx: &mut ModelContext<Self>,
1609    ) {
1610        self.reparse_slash_commands(cx);
1611
1612        let insert_output_task = cx.spawn(|this, mut cx| {
1613            let command_range = command_range.clone();
1614            async move {
1615                let output = output.await;
1616                this.update(&mut cx, |this, cx| match output {
1617                    Ok(mut output) => {
1618                        if insert_trailing_newline {
1619                            output.text.push('\n');
1620                        }
1621
1622                        let version = this.version.clone();
1623                        let command_id = SlashCommandId(this.next_timestamp());
1624                        let (operation, event) = this.buffer.update(cx, |buffer, cx| {
1625                            let start = command_range.start.to_offset(buffer);
1626                            let old_end = command_range.end.to_offset(buffer);
1627                            let new_end = start + output.text.len();
1628                            buffer.edit([(start..old_end, output.text)], None, cx);
1629
1630                            let mut sections = output
1631                                .sections
1632                                .into_iter()
1633                                .map(|section| SlashCommandOutputSection {
1634                                    range: buffer.anchor_after(start + section.range.start)
1635                                        ..buffer.anchor_before(start + section.range.end),
1636                                    icon: section.icon,
1637                                    label: section.label,
1638                                })
1639                                .collect::<Vec<_>>();
1640                            sections.sort_by(|a, b| a.range.cmp(&b.range, buffer));
1641
1642                            this.slash_command_output_sections
1643                                .extend(sections.iter().cloned());
1644                            this.slash_command_output_sections
1645                                .sort_by(|a, b| a.range.cmp(&b.range, buffer));
1646
1647                            let output_range =
1648                                buffer.anchor_after(start)..buffer.anchor_before(new_end);
1649                            this.finished_slash_commands.insert(command_id);
1650
1651                            (
1652                                ContextOperation::SlashCommandFinished {
1653                                    id: command_id,
1654                                    output_range: output_range.clone(),
1655                                    sections: sections.clone(),
1656                                    version,
1657                                },
1658                                ContextEvent::SlashCommandFinished {
1659                                    output_range,
1660                                    sections,
1661                                    run_commands_in_output: output.run_commands_in_text,
1662                                },
1663                            )
1664                        });
1665
1666                        this.push_op(operation, cx);
1667                        cx.emit(event);
1668                    }
1669                    Err(error) => {
1670                        if let Some(pending_command) =
1671                            this.pending_command_for_position(command_range.start, cx)
1672                        {
1673                            pending_command.status =
1674                                PendingSlashCommandStatus::Error(error.to_string());
1675                            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1676                                removed: vec![pending_command.source_range.clone()],
1677                                updated: vec![pending_command.clone()],
1678                            });
1679                        }
1680                    }
1681                })
1682                .ok();
1683            }
1684        });
1685
1686        if let Some(pending_command) = self.pending_command_for_position(command_range.start, cx) {
1687            pending_command.status = PendingSlashCommandStatus::Running {
1688                _task: insert_output_task.shared(),
1689            };
1690            cx.emit(ContextEvent::PendingSlashCommandsUpdated {
1691                removed: vec![pending_command.source_range.clone()],
1692                updated: vec![pending_command.clone()],
1693            });
1694        }
1695    }
1696
1697    pub fn completion_provider_changed(&mut self, cx: &mut ModelContext<Self>) {
1698        self.count_remaining_tokens(cx);
1699    }
1700
1701    pub fn assist(&mut self, cx: &mut ModelContext<Self>) -> Option<MessageAnchor> {
1702        let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
1703        let model = LanguageModelRegistry::read_global(cx).active_model()?;
1704        let last_message_id = self.message_anchors.iter().rev().find_map(|message| {
1705            message
1706                .start
1707                .is_valid(self.buffer.read(cx))
1708                .then_some(message.id)
1709        })?;
1710
1711        if !provider.is_authenticated(cx) {
1712            log::info!("completion provider has no credentials");
1713            return None;
1714        }
1715
1716        let request = self.to_completion_request(cx);
1717        let assistant_message = self
1718            .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1719            .unwrap();
1720
1721        // Queue up the user's next reply.
1722        let user_message = self
1723            .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
1724            .unwrap();
1725
1726        let pending_completion_id = post_inc(&mut self.completion_count);
1727
1728        let task = cx.spawn({
1729            |this, mut cx| async move {
1730                let stream = model.stream_completion(request, &cx);
1731                let assistant_message_id = assistant_message.id;
1732                let mut response_latency = None;
1733                let stream_completion = async {
1734                    let request_start = Instant::now();
1735                    let mut chunks = stream.await?;
1736
1737                    while let Some(chunk) = chunks.next().await {
1738                        if response_latency.is_none() {
1739                            response_latency = Some(request_start.elapsed());
1740                        }
1741                        let chunk = chunk?;
1742
1743                        this.update(&mut cx, |this, cx| {
1744                            let message_ix = this
1745                                .message_anchors
1746                                .iter()
1747                                .position(|message| message.id == assistant_message_id)?;
1748                            let message_range = this.buffer.update(cx, |buffer, cx| {
1749                                let message_start_offset =
1750                                    this.message_anchors[message_ix].start.to_offset(buffer);
1751                                let message_old_end_offset = this.message_anchors[message_ix + 1..]
1752                                    .iter()
1753                                    .find(|message| message.start.is_valid(buffer))
1754                                    .map_or(buffer.len(), |message| {
1755                                        message.start.to_offset(buffer).saturating_sub(1)
1756                                    });
1757                                let message_new_end_offset = message_old_end_offset + chunk.len();
1758                                buffer.edit(
1759                                    [(message_old_end_offset..message_old_end_offset, chunk)],
1760                                    None,
1761                                    cx,
1762                                );
1763                                message_start_offset..message_new_end_offset
1764                            });
1765                            if let Some(project) = this.project.clone() {
1766                                // Use `inclusive = false` as edits might occur at the end of a parsed step.
1767                                this.prune_invalid_workflow_steps(false, cx);
1768                                this.parse_workflow_steps_in_range(message_range, project, cx);
1769                            }
1770                            cx.emit(ContextEvent::StreamedCompletion);
1771
1772                            Some(())
1773                        })?;
1774                        smol::future::yield_now().await;
1775                    }
1776                    this.update(&mut cx, |this, cx| {
1777                        this.pending_completions
1778                            .retain(|completion| completion.id != pending_completion_id);
1779                        this.summarize(false, cx);
1780                    })?;
1781
1782                    anyhow::Ok(())
1783                };
1784
1785                let result = stream_completion.await;
1786
1787                this.update(&mut cx, |this, cx| {
1788                    let error_message = result
1789                        .err()
1790                        .map(|error| error.to_string().trim().to_string());
1791
1792                    if let Some(error_message) = error_message.as_ref() {
1793                        cx.emit(ContextEvent::AssistError(error_message.to_string()));
1794                    }
1795
1796                    this.update_metadata(assistant_message_id, cx, |metadata| {
1797                        if let Some(error_message) = error_message.as_ref() {
1798                            metadata.status =
1799                                MessageStatus::Error(SharedString::from(error_message.clone()));
1800                        } else {
1801                            metadata.status = MessageStatus::Done;
1802                        }
1803                    });
1804
1805                    if let Some(telemetry) = this.telemetry.as_ref() {
1806                        telemetry.report_assistant_event(
1807                            Some(this.id.0.clone()),
1808                            AssistantKind::Panel,
1809                            model.telemetry_id(),
1810                            response_latency,
1811                            error_message,
1812                        );
1813                    }
1814                })
1815                .ok();
1816            }
1817        });
1818
1819        self.pending_completions.push(PendingCompletion {
1820            id: pending_completion_id,
1821            assistant_message_id: assistant_message.id,
1822            _task: task,
1823        });
1824
1825        Some(user_message)
1826    }
1827
1828    pub fn to_completion_request(&self, cx: &AppContext) -> LanguageModelRequest {
1829        let buffer = self.buffer.read(cx);
1830        let request_messages = self
1831            .messages(cx)
1832            .filter(|message| message.status == MessageStatus::Done)
1833            .map(|message| message.to_request_message(&buffer))
1834            .collect();
1835
1836        LanguageModelRequest {
1837            messages: request_messages,
1838            stop: vec![],
1839            temperature: 1.0,
1840        }
1841    }
1842
1843    pub fn cancel_last_assist(&mut self, cx: &mut ModelContext<Self>) -> bool {
1844        if let Some(pending_completion) = self.pending_completions.pop() {
1845            self.update_metadata(pending_completion.assistant_message_id, cx, |metadata| {
1846                metadata.status = MessageStatus::Canceled;
1847            });
1848            true
1849        } else {
1850            false
1851        }
1852    }
1853
1854    pub fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
1855        for id in ids {
1856            if let Some(metadata) = self.messages_metadata.get(&id) {
1857                let role = metadata.role.cycle();
1858                self.update_metadata(id, cx, |metadata| metadata.role = role);
1859            }
1860        }
1861    }
1862
1863    pub fn update_metadata(
1864        &mut self,
1865        id: MessageId,
1866        cx: &mut ModelContext<Self>,
1867        f: impl FnOnce(&mut MessageMetadata),
1868    ) {
1869        let version = self.version.clone();
1870        let timestamp = self.next_timestamp();
1871        if let Some(metadata) = self.messages_metadata.get_mut(&id) {
1872            f(metadata);
1873            metadata.timestamp = timestamp;
1874            let operation = ContextOperation::UpdateMessage {
1875                message_id: id,
1876                metadata: metadata.clone(),
1877                version,
1878            };
1879            self.push_op(operation, cx);
1880            cx.emit(ContextEvent::MessagesEdited);
1881            cx.notify();
1882        }
1883    }
1884
1885    fn insert_message_after(
1886        &mut self,
1887        message_id: MessageId,
1888        role: Role,
1889        status: MessageStatus,
1890        cx: &mut ModelContext<Self>,
1891    ) -> Option<MessageAnchor> {
1892        if let Some(prev_message_ix) = self
1893            .message_anchors
1894            .iter()
1895            .position(|message| message.id == message_id)
1896        {
1897            // Find the next valid message after the one we were given.
1898            let mut next_message_ix = prev_message_ix + 1;
1899            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
1900                if next_message.start.is_valid(self.buffer.read(cx)) {
1901                    break;
1902                }
1903                next_message_ix += 1;
1904            }
1905
1906            let start = self.buffer.update(cx, |buffer, cx| {
1907                let offset = self
1908                    .message_anchors
1909                    .get(next_message_ix)
1910                    .map_or(buffer.len(), |message| {
1911                        buffer.clip_offset(message.start.to_offset(buffer) - 1, Bias::Left)
1912                    });
1913                buffer.edit([(offset..offset, "\n")], None, cx);
1914                buffer.anchor_before(offset + 1)
1915            });
1916
1917            let version = self.version.clone();
1918            let anchor = MessageAnchor {
1919                id: MessageId(self.next_timestamp()),
1920                start,
1921            };
1922            let metadata = MessageMetadata {
1923                role,
1924                status,
1925                timestamp: anchor.id.0,
1926            };
1927            self.insert_message(anchor.clone(), metadata.clone(), cx);
1928            self.push_op(
1929                ContextOperation::InsertMessage {
1930                    anchor: anchor.clone(),
1931                    metadata,
1932                    version,
1933                },
1934                cx,
1935            );
1936            Some(anchor)
1937        } else {
1938            None
1939        }
1940    }
1941
1942    pub fn insert_image(&mut self, image: Image, cx: &mut ModelContext<Self>) -> Option<()> {
1943        if let hash_map::Entry::Vacant(entry) = self.images.entry(image.id()) {
1944            entry.insert((
1945                image.to_image_data(cx).log_err()?,
1946                LanguageModelImage::from_image(image, cx).shared(),
1947            ));
1948        }
1949
1950        Some(())
1951    }
1952
1953    pub fn insert_image_anchor(
1954        &mut self,
1955        image_id: u64,
1956        anchor: language::Anchor,
1957        cx: &mut ModelContext<Self>,
1958    ) -> bool {
1959        cx.emit(ContextEvent::MessagesEdited);
1960
1961        let buffer = self.buffer.read(cx);
1962        let insertion_ix = match self
1963            .image_anchors
1964            .binary_search_by(|existing_anchor| anchor.cmp(&existing_anchor.anchor, buffer))
1965        {
1966            Ok(ix) => ix,
1967            Err(ix) => ix,
1968        };
1969
1970        if let Some((render_image, image)) = self.images.get(&image_id) {
1971            self.image_anchors.insert(
1972                insertion_ix,
1973                ImageAnchor {
1974                    anchor,
1975                    image_id,
1976                    image: image.clone(),
1977                    render_image: render_image.clone(),
1978                },
1979            );
1980
1981            true
1982        } else {
1983            false
1984        }
1985    }
1986
1987    pub fn images<'a>(&'a self, _cx: &'a AppContext) -> impl 'a + Iterator<Item = ImageAnchor> {
1988        self.image_anchors.iter().cloned()
1989    }
1990
1991    pub fn split_message(
1992        &mut self,
1993        range: Range<usize>,
1994        cx: &mut ModelContext<Self>,
1995    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
1996        let start_message = self.message_for_offset(range.start, cx);
1997        let end_message = self.message_for_offset(range.end, cx);
1998        if let Some((start_message, end_message)) = start_message.zip(end_message) {
1999            // Prevent splitting when range spans multiple messages.
2000            if start_message.id != end_message.id {
2001                return (None, None);
2002            }
2003
2004            let message = start_message;
2005            let role = message.role;
2006            let mut edited_buffer = false;
2007
2008            let mut suffix_start = None;
2009
2010            // TODO: why did this start panicking?
2011            if range.start > message.offset_range.start
2012                && range.end < message.offset_range.end.saturating_sub(1)
2013            {
2014                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
2015                    suffix_start = Some(range.end + 1);
2016                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
2017                    suffix_start = Some(range.end);
2018                }
2019            }
2020
2021            let version = self.version.clone();
2022            let suffix = if let Some(suffix_start) = suffix_start {
2023                MessageAnchor {
2024                    id: MessageId(self.next_timestamp()),
2025                    start: self.buffer.read(cx).anchor_before(suffix_start),
2026                }
2027            } else {
2028                self.buffer.update(cx, |buffer, cx| {
2029                    buffer.edit([(range.end..range.end, "\n")], None, cx);
2030                });
2031                edited_buffer = true;
2032                MessageAnchor {
2033                    id: MessageId(self.next_timestamp()),
2034                    start: self.buffer.read(cx).anchor_before(range.end + 1),
2035                }
2036            };
2037
2038            let suffix_metadata = MessageMetadata {
2039                role,
2040                status: MessageStatus::Done,
2041                timestamp: suffix.id.0,
2042            };
2043            self.insert_message(suffix.clone(), suffix_metadata.clone(), cx);
2044            self.push_op(
2045                ContextOperation::InsertMessage {
2046                    anchor: suffix.clone(),
2047                    metadata: suffix_metadata,
2048                    version,
2049                },
2050                cx,
2051            );
2052
2053            let new_messages =
2054                if range.start == range.end || range.start == message.offset_range.start {
2055                    (None, Some(suffix))
2056                } else {
2057                    let mut prefix_end = None;
2058                    if range.start > message.offset_range.start
2059                        && range.end < message.offset_range.end - 1
2060                    {
2061                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
2062                            prefix_end = Some(range.start + 1);
2063                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
2064                            == Some('\n')
2065                        {
2066                            prefix_end = Some(range.start);
2067                        }
2068                    }
2069
2070                    let version = self.version.clone();
2071                    let selection = if let Some(prefix_end) = prefix_end {
2072                        MessageAnchor {
2073                            id: MessageId(self.next_timestamp()),
2074                            start: self.buffer.read(cx).anchor_before(prefix_end),
2075                        }
2076                    } else {
2077                        self.buffer.update(cx, |buffer, cx| {
2078                            buffer.edit([(range.start..range.start, "\n")], None, cx)
2079                        });
2080                        edited_buffer = true;
2081                        MessageAnchor {
2082                            id: MessageId(self.next_timestamp()),
2083                            start: self.buffer.read(cx).anchor_before(range.end + 1),
2084                        }
2085                    };
2086
2087                    let selection_metadata = MessageMetadata {
2088                        role,
2089                        status: MessageStatus::Done,
2090                        timestamp: selection.id.0,
2091                    };
2092                    self.insert_message(selection.clone(), selection_metadata.clone(), cx);
2093                    self.push_op(
2094                        ContextOperation::InsertMessage {
2095                            anchor: selection.clone(),
2096                            metadata: selection_metadata,
2097                            version,
2098                        },
2099                        cx,
2100                    );
2101
2102                    (Some(selection), Some(suffix))
2103                };
2104
2105            if !edited_buffer {
2106                cx.emit(ContextEvent::MessagesEdited);
2107            }
2108            new_messages
2109        } else {
2110            (None, None)
2111        }
2112    }
2113
2114    fn insert_message(
2115        &mut self,
2116        new_anchor: MessageAnchor,
2117        new_metadata: MessageMetadata,
2118        cx: &mut ModelContext<Self>,
2119    ) {
2120        cx.emit(ContextEvent::MessagesEdited);
2121
2122        self.messages_metadata.insert(new_anchor.id, new_metadata);
2123
2124        let buffer = self.buffer.read(cx);
2125        let insertion_ix = self
2126            .message_anchors
2127            .iter()
2128            .position(|anchor| {
2129                let comparison = new_anchor.start.cmp(&anchor.start, buffer);
2130                comparison.is_lt() || (comparison.is_eq() && new_anchor.id > anchor.id)
2131            })
2132            .unwrap_or(self.message_anchors.len());
2133        self.message_anchors.insert(insertion_ix, new_anchor);
2134    }
2135
2136    pub(super) fn summarize(&mut self, replace_old: bool, cx: &mut ModelContext<Self>) {
2137        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
2138            return;
2139        };
2140        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
2141            return;
2142        };
2143
2144        if replace_old || (self.message_anchors.len() >= 2 && self.summary.is_none()) {
2145            if !provider.is_authenticated(cx) {
2146                return;
2147            }
2148
2149            let messages = self
2150                .messages(cx)
2151                .map(|message| message.to_request_message(self.buffer.read(cx)))
2152                .chain(Some(LanguageModelRequestMessage {
2153                    role: Role::User,
2154                    content: vec![
2155                        "Summarize the context into a short title without punctuation.".into(),
2156                    ],
2157                }));
2158            let request = LanguageModelRequest {
2159                messages: messages.collect(),
2160                stop: vec![],
2161                temperature: 1.0,
2162            };
2163
2164            self.pending_summary = cx.spawn(|this, mut cx| {
2165                async move {
2166                    let stream = model.stream_completion(request, &cx);
2167                    let mut messages = stream.await?;
2168
2169                    let mut replaced = !replace_old;
2170                    while let Some(message) = messages.next().await {
2171                        let text = message?;
2172                        let mut lines = text.lines();
2173                        this.update(&mut cx, |this, cx| {
2174                            let version = this.version.clone();
2175                            let timestamp = this.next_timestamp();
2176                            let summary = this.summary.get_or_insert(ContextSummary::default());
2177                            if !replaced && replace_old {
2178                                summary.text.clear();
2179                                replaced = true;
2180                            }
2181                            summary.text.extend(lines.next());
2182                            summary.timestamp = timestamp;
2183                            let operation = ContextOperation::UpdateSummary {
2184                                summary: summary.clone(),
2185                                version,
2186                            };
2187                            this.push_op(operation, cx);
2188                            cx.emit(ContextEvent::SummaryChanged);
2189                        })?;
2190
2191                        // Stop if the LLM generated multiple lines.
2192                        if lines.next().is_some() {
2193                            break;
2194                        }
2195                    }
2196
2197                    this.update(&mut cx, |this, cx| {
2198                        let version = this.version.clone();
2199                        let timestamp = this.next_timestamp();
2200                        if let Some(summary) = this.summary.as_mut() {
2201                            summary.done = true;
2202                            summary.timestamp = timestamp;
2203                            let operation = ContextOperation::UpdateSummary {
2204                                summary: summary.clone(),
2205                                version,
2206                            };
2207                            this.push_op(operation, cx);
2208                            cx.emit(ContextEvent::SummaryChanged);
2209                        }
2210                    })?;
2211
2212                    anyhow::Ok(())
2213                }
2214                .log_err()
2215            });
2216        }
2217    }
2218
2219    fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
2220        self.messages_for_offsets([offset], cx).pop()
2221    }
2222
2223    pub fn messages_for_offsets(
2224        &self,
2225        offsets: impl IntoIterator<Item = usize>,
2226        cx: &AppContext,
2227    ) -> Vec<Message> {
2228        let mut result = Vec::new();
2229
2230        let mut messages = self.messages(cx).peekable();
2231        let mut offsets = offsets.into_iter().peekable();
2232        let mut current_message = messages.next();
2233        while let Some(offset) = offsets.next() {
2234            // Locate the message that contains the offset.
2235            while current_message.as_ref().map_or(false, |message| {
2236                !message.offset_range.contains(&offset) && messages.peek().is_some()
2237            }) {
2238                current_message = messages.next();
2239            }
2240            let Some(message) = current_message.as_ref() else {
2241                break;
2242            };
2243
2244            // Skip offsets that are in the same message.
2245            while offsets.peek().map_or(false, |offset| {
2246                message.offset_range.contains(offset) || messages.peek().is_none()
2247            }) {
2248                offsets.next();
2249            }
2250
2251            result.push(message.clone());
2252        }
2253        result
2254    }
2255
2256    pub fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
2257        let buffer = self.buffer.read(cx);
2258        let messages = self.message_anchors.iter().enumerate();
2259        let images = self.image_anchors.iter();
2260
2261        Self::messages_from_iters(buffer, &self.messages_metadata, messages, images)
2262    }
2263
2264    pub fn messages_from_iters<'a>(
2265        buffer: &'a Buffer,
2266        metadata: &'a HashMap<MessageId, MessageMetadata>,
2267        messages: impl Iterator<Item = (usize, &'a MessageAnchor)> + 'a,
2268        images: impl Iterator<Item = &'a ImageAnchor> + 'a,
2269    ) -> impl 'a + Iterator<Item = Message> {
2270        let mut messages = messages.peekable();
2271        let mut images = images.peekable();
2272
2273        iter::from_fn(move || {
2274            if let Some((start_ix, message_anchor)) = messages.next() {
2275                let metadata = metadata.get(&message_anchor.id)?;
2276
2277                let message_start = message_anchor.start.to_offset(buffer);
2278                let mut message_end = None;
2279                let mut end_ix = start_ix;
2280                while let Some((_, next_message)) = messages.peek() {
2281                    if next_message.start.is_valid(buffer) {
2282                        message_end = Some(next_message.start);
2283                        break;
2284                    } else {
2285                        end_ix += 1;
2286                        messages.next();
2287                    }
2288                }
2289                let message_end_anchor = message_end.unwrap_or(language::Anchor::MAX);
2290                let message_end = message_end_anchor.to_offset(buffer);
2291
2292                let mut image_offsets = SmallVec::new();
2293                while let Some(image_anchor) = images.peek() {
2294                    if image_anchor.anchor.cmp(&message_end_anchor, buffer).is_lt() {
2295                        image_offsets.push((
2296                            image_anchor.anchor.to_offset(buffer),
2297                            MessageImage {
2298                                image_id: image_anchor.image_id,
2299                                image: image_anchor.image.clone(),
2300                            },
2301                        ));
2302                        images.next();
2303                    } else {
2304                        break;
2305                    }
2306                }
2307
2308                return Some(Message {
2309                    index_range: start_ix..end_ix,
2310                    offset_range: message_start..message_end,
2311                    id: message_anchor.id,
2312                    anchor: message_anchor.start,
2313                    role: metadata.role,
2314                    status: metadata.status.clone(),
2315                    image_offsets,
2316                });
2317            }
2318            None
2319        })
2320    }
2321
2322    pub fn save(
2323        &mut self,
2324        debounce: Option<Duration>,
2325        fs: Arc<dyn Fs>,
2326        cx: &mut ModelContext<Context>,
2327    ) {
2328        if self.replica_id() != ReplicaId::default() {
2329            // Prevent saving a remote context for now.
2330            return;
2331        }
2332
2333        self.pending_save = cx.spawn(|this, mut cx| async move {
2334            if let Some(debounce) = debounce {
2335                cx.background_executor().timer(debounce).await;
2336            }
2337
2338            let (old_path, summary) = this.read_with(&cx, |this, _| {
2339                let path = this.path.clone();
2340                let summary = if let Some(summary) = this.summary.as_ref() {
2341                    if summary.done {
2342                        Some(summary.text.clone())
2343                    } else {
2344                        None
2345                    }
2346                } else {
2347                    None
2348                };
2349                (path, summary)
2350            })?;
2351
2352            if let Some(summary) = summary {
2353                this.read_with(&cx, |this, cx| this.serialize_images(fs.clone(), cx))?
2354                    .await;
2355
2356                let context = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2357                let mut discriminant = 1;
2358                let mut new_path;
2359                loop {
2360                    new_path = contexts_dir().join(&format!(
2361                        "{} - {}.zed.json",
2362                        summary.trim(),
2363                        discriminant
2364                    ));
2365                    if fs.is_file(&new_path).await {
2366                        discriminant += 1;
2367                    } else {
2368                        break;
2369                    }
2370                }
2371
2372                fs.create_dir(contexts_dir().as_ref()).await?;
2373                fs.atomic_write(new_path.clone(), serde_json::to_string(&context).unwrap())
2374                    .await?;
2375                if let Some(old_path) = old_path {
2376                    if new_path != old_path {
2377                        fs.remove_file(
2378                            &old_path,
2379                            RemoveOptions {
2380                                recursive: false,
2381                                ignore_if_not_exists: true,
2382                            },
2383                        )
2384                        .await?;
2385                    }
2386                }
2387
2388                this.update(&mut cx, |this, _| this.path = Some(new_path))?;
2389            }
2390
2391            Ok(())
2392        });
2393    }
2394
2395    pub fn serialize_images(&self, fs: Arc<dyn Fs>, cx: &AppContext) -> Task<()> {
2396        let mut images_to_save = self
2397            .images
2398            .iter()
2399            .map(|(id, (_, llm_image))| {
2400                let fs = fs.clone();
2401                let llm_image = llm_image.clone();
2402                let id = *id;
2403                async move {
2404                    if let Some(llm_image) = llm_image.await {
2405                        let path: PathBuf =
2406                            context_images_dir().join(&format!("{}.png.base64", id));
2407                        if fs
2408                            .metadata(path.as_path())
2409                            .await
2410                            .log_err()
2411                            .flatten()
2412                            .is_none()
2413                        {
2414                            fs.atomic_write(path, llm_image.source.to_string())
2415                                .await
2416                                .log_err();
2417                        }
2418                    }
2419                }
2420            })
2421            .collect::<FuturesUnordered<_>>();
2422        cx.background_executor().spawn(async move {
2423            if fs
2424                .create_dir(context_images_dir().as_ref())
2425                .await
2426                .log_err()
2427                .is_some()
2428            {
2429                while let Some(_) = images_to_save.next().await {}
2430            }
2431        })
2432    }
2433
2434    pub(crate) fn custom_summary(&mut self, custom_summary: String, cx: &mut ModelContext<Self>) {
2435        let timestamp = self.next_timestamp();
2436        let summary = self.summary.get_or_insert(ContextSummary::default());
2437        summary.timestamp = timestamp;
2438        summary.done = true;
2439        summary.text = custom_summary;
2440        cx.emit(ContextEvent::SummaryChanged);
2441    }
2442}
2443
2444#[derive(Debug, Default)]
2445pub struct ContextVersion {
2446    context: clock::Global,
2447    buffer: clock::Global,
2448}
2449
2450impl ContextVersion {
2451    pub fn from_proto(proto: &proto::ContextVersion) -> Self {
2452        Self {
2453            context: language::proto::deserialize_version(&proto.context_version),
2454            buffer: language::proto::deserialize_version(&proto.buffer_version),
2455        }
2456    }
2457
2458    pub fn to_proto(&self, context_id: ContextId) -> proto::ContextVersion {
2459        proto::ContextVersion {
2460            context_id: context_id.to_proto(),
2461            context_version: language::proto::serialize_version(&self.context),
2462            buffer_version: language::proto::serialize_version(&self.buffer),
2463        }
2464    }
2465}
2466
2467#[derive(Debug, Clone)]
2468pub struct PendingSlashCommand {
2469    pub name: String,
2470    pub arguments: SmallVec<[String; 3]>,
2471    pub status: PendingSlashCommandStatus,
2472    pub source_range: Range<language::Anchor>,
2473}
2474
2475#[derive(Debug, Clone)]
2476pub enum PendingSlashCommandStatus {
2477    Idle,
2478    Running { _task: Shared<Task<()>> },
2479    Error(String),
2480}
2481
2482#[derive(Serialize, Deserialize)]
2483pub struct SavedMessage {
2484    pub id: MessageId,
2485    pub start: usize,
2486    pub metadata: MessageMetadata,
2487    #[serde(default)]
2488    // This is defaulted for backwards compatibility with JSON files created before August 2024. We didn't always have this field.
2489    pub image_offsets: Vec<(usize, u64)>,
2490}
2491
2492#[derive(Serialize, Deserialize)]
2493pub struct SavedContext {
2494    pub id: Option<ContextId>,
2495    pub zed: String,
2496    pub version: String,
2497    pub text: String,
2498    pub messages: Vec<SavedMessage>,
2499    pub summary: String,
2500    pub slash_command_output_sections:
2501        Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2502}
2503
2504impl SavedContext {
2505    pub const VERSION: &'static str = "0.4.0";
2506
2507    pub fn from_json(json: &str) -> Result<Self> {
2508        let saved_context_json = serde_json::from_str::<serde_json::Value>(json)?;
2509        match saved_context_json
2510            .get("version")
2511            .ok_or_else(|| anyhow!("version not found"))?
2512        {
2513            serde_json::Value::String(version) => match version.as_str() {
2514                SavedContext::VERSION => {
2515                    Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
2516                }
2517                SavedContextV0_3_0::VERSION => {
2518                    let saved_context =
2519                        serde_json::from_value::<SavedContextV0_3_0>(saved_context_json)?;
2520                    Ok(saved_context.upgrade())
2521                }
2522                SavedContextV0_2_0::VERSION => {
2523                    let saved_context =
2524                        serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
2525                    Ok(saved_context.upgrade())
2526                }
2527                SavedContextV0_1_0::VERSION => {
2528                    let saved_context =
2529                        serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
2530                    Ok(saved_context.upgrade())
2531                }
2532                _ => Err(anyhow!("unrecognized saved context version: {}", version)),
2533            },
2534            _ => Err(anyhow!("version not found on saved context")),
2535        }
2536    }
2537
2538    fn into_ops(
2539        self,
2540        buffer: &Model<Buffer>,
2541        cx: &mut ModelContext<Context>,
2542    ) -> Vec<ContextOperation> {
2543        let mut operations = Vec::new();
2544        let mut version = clock::Global::new();
2545        let mut next_timestamp = clock::Lamport::new(ReplicaId::default());
2546
2547        let mut first_message_metadata = None;
2548        for message in self.messages {
2549            if message.id == MessageId(clock::Lamport::default()) {
2550                first_message_metadata = Some(message.metadata);
2551            } else {
2552                operations.push(ContextOperation::InsertMessage {
2553                    anchor: MessageAnchor {
2554                        id: message.id,
2555                        start: buffer.read(cx).anchor_before(message.start),
2556                    },
2557                    metadata: MessageMetadata {
2558                        role: message.metadata.role,
2559                        status: message.metadata.status,
2560                        timestamp: message.metadata.timestamp,
2561                    },
2562                    version: version.clone(),
2563                });
2564                version.observe(message.id.0);
2565                next_timestamp.observe(message.id.0);
2566            }
2567        }
2568
2569        if let Some(metadata) = first_message_metadata {
2570            let timestamp = next_timestamp.tick();
2571            operations.push(ContextOperation::UpdateMessage {
2572                message_id: MessageId(clock::Lamport::default()),
2573                metadata: MessageMetadata {
2574                    role: metadata.role,
2575                    status: metadata.status,
2576                    timestamp,
2577                },
2578                version: version.clone(),
2579            });
2580            version.observe(timestamp);
2581        }
2582
2583        let timestamp = next_timestamp.tick();
2584        operations.push(ContextOperation::SlashCommandFinished {
2585            id: SlashCommandId(timestamp),
2586            output_range: language::Anchor::MIN..language::Anchor::MAX,
2587            sections: self
2588                .slash_command_output_sections
2589                .into_iter()
2590                .map(|section| {
2591                    let buffer = buffer.read(cx);
2592                    SlashCommandOutputSection {
2593                        range: buffer.anchor_after(section.range.start)
2594                            ..buffer.anchor_before(section.range.end),
2595                        icon: section.icon,
2596                        label: section.label,
2597                    }
2598                })
2599                .collect(),
2600            version: version.clone(),
2601        });
2602        version.observe(timestamp);
2603
2604        let timestamp = next_timestamp.tick();
2605        operations.push(ContextOperation::UpdateSummary {
2606            summary: ContextSummary {
2607                text: self.summary,
2608                done: true,
2609                timestamp,
2610            },
2611            version: version.clone(),
2612        });
2613        version.observe(timestamp);
2614
2615        operations
2616    }
2617}
2618
2619#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
2620struct SavedMessageIdPreV0_4_0(usize);
2621
2622#[derive(Serialize, Deserialize)]
2623struct SavedMessagePreV0_4_0 {
2624    id: SavedMessageIdPreV0_4_0,
2625    start: usize,
2626}
2627
2628#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2629struct SavedMessageMetadataPreV0_4_0 {
2630    role: Role,
2631    status: MessageStatus,
2632}
2633
2634#[derive(Serialize, Deserialize)]
2635struct SavedContextV0_3_0 {
2636    id: Option<ContextId>,
2637    zed: String,
2638    version: String,
2639    text: String,
2640    messages: Vec<SavedMessagePreV0_4_0>,
2641    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2642    summary: String,
2643    slash_command_output_sections: Vec<assistant_slash_command::SlashCommandOutputSection<usize>>,
2644}
2645
2646impl SavedContextV0_3_0 {
2647    const VERSION: &'static str = "0.3.0";
2648
2649    fn upgrade(self) -> SavedContext {
2650        SavedContext {
2651            id: self.id,
2652            zed: self.zed,
2653            version: SavedContext::VERSION.into(),
2654            text: self.text,
2655            messages: self
2656                .messages
2657                .into_iter()
2658                .filter_map(|message| {
2659                    let metadata = self.message_metadata.get(&message.id)?;
2660                    let timestamp = clock::Lamport {
2661                        replica_id: ReplicaId::default(),
2662                        value: message.id.0 as u32,
2663                    };
2664                    Some(SavedMessage {
2665                        id: MessageId(timestamp),
2666                        start: message.start,
2667                        metadata: MessageMetadata {
2668                            role: metadata.role,
2669                            status: metadata.status.clone(),
2670                            timestamp,
2671                        },
2672                        image_offsets: Vec::new(),
2673                    })
2674                })
2675                .collect(),
2676            summary: self.summary,
2677            slash_command_output_sections: self.slash_command_output_sections,
2678        }
2679    }
2680}
2681
2682#[derive(Serialize, Deserialize)]
2683struct SavedContextV0_2_0 {
2684    id: Option<ContextId>,
2685    zed: String,
2686    version: String,
2687    text: String,
2688    messages: Vec<SavedMessagePreV0_4_0>,
2689    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2690    summary: String,
2691}
2692
2693impl SavedContextV0_2_0 {
2694    const VERSION: &'static str = "0.2.0";
2695
2696    fn upgrade(self) -> SavedContext {
2697        SavedContextV0_3_0 {
2698            id: self.id,
2699            zed: self.zed,
2700            version: SavedContextV0_3_0::VERSION.to_string(),
2701            text: self.text,
2702            messages: self.messages,
2703            message_metadata: self.message_metadata,
2704            summary: self.summary,
2705            slash_command_output_sections: Vec::new(),
2706        }
2707        .upgrade()
2708    }
2709}
2710
2711#[derive(Serialize, Deserialize)]
2712struct SavedContextV0_1_0 {
2713    id: Option<ContextId>,
2714    zed: String,
2715    version: String,
2716    text: String,
2717    messages: Vec<SavedMessagePreV0_4_0>,
2718    message_metadata: HashMap<SavedMessageIdPreV0_4_0, SavedMessageMetadataPreV0_4_0>,
2719    summary: String,
2720    api_url: Option<String>,
2721    model: OpenAiModel,
2722}
2723
2724impl SavedContextV0_1_0 {
2725    const VERSION: &'static str = "0.1.0";
2726
2727    fn upgrade(self) -> SavedContext {
2728        SavedContextV0_2_0 {
2729            id: self.id,
2730            zed: self.zed,
2731            version: SavedContextV0_2_0::VERSION.to_string(),
2732            text: self.text,
2733            messages: self.messages,
2734            message_metadata: self.message_metadata,
2735            summary: self.summary,
2736        }
2737        .upgrade()
2738    }
2739}
2740
2741#[derive(Clone)]
2742pub struct SavedContextMetadata {
2743    pub title: String,
2744    pub path: PathBuf,
2745    pub mtime: chrono::DateTime<chrono::Local>,
2746}
2747
2748#[cfg(test)]
2749mod tests {
2750    use super::*;
2751    use crate::{assistant_panel, prompt_library, slash_command::file_command, MessageId};
2752    use assistant_slash_command::{ArgumentCompletion, SlashCommand};
2753    use fs::FakeFs;
2754    use gpui::{AppContext, TestAppContext, WeakView};
2755    use indoc::indoc;
2756    use language::LspAdapterDelegate;
2757    use parking_lot::Mutex;
2758    use project::Project;
2759    use rand::prelude::*;
2760    use serde_json::json;
2761    use settings::SettingsStore;
2762    use std::{cell::RefCell, env, rc::Rc, sync::atomic::AtomicBool};
2763    use text::{network::Network, ToPoint};
2764    use ui::WindowContext;
2765    use unindent::Unindent;
2766    use util::{test::marked_text_ranges, RandomCharIter};
2767    use workspace::Workspace;
2768
2769    #[gpui::test]
2770    fn test_inserting_and_removing_messages(cx: &mut AppContext) {
2771        let settings_store = SettingsStore::test(cx);
2772        LanguageModelRegistry::test(cx);
2773        cx.set_global(settings_store);
2774        assistant_panel::init(cx);
2775        let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2776        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2777        let context =
2778            cx.new_model(|cx| Context::local(registry, None, None, prompt_builder.clone(), cx));
2779        let buffer = context.read(cx).buffer.clone();
2780
2781        let message_1 = context.read(cx).message_anchors[0].clone();
2782        assert_eq!(
2783            messages(&context, cx),
2784            vec![(message_1.id, Role::User, 0..0)]
2785        );
2786
2787        let message_2 = context.update(cx, |context, cx| {
2788            context
2789                .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx)
2790                .unwrap()
2791        });
2792        assert_eq!(
2793            messages(&context, cx),
2794            vec![
2795                (message_1.id, Role::User, 0..1),
2796                (message_2.id, Role::Assistant, 1..1)
2797            ]
2798        );
2799
2800        buffer.update(cx, |buffer, cx| {
2801            buffer.edit([(0..0, "1"), (1..1, "2")], None, cx)
2802        });
2803        assert_eq!(
2804            messages(&context, cx),
2805            vec![
2806                (message_1.id, Role::User, 0..2),
2807                (message_2.id, Role::Assistant, 2..3)
2808            ]
2809        );
2810
2811        let message_3 = context.update(cx, |context, cx| {
2812            context
2813                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2814                .unwrap()
2815        });
2816        assert_eq!(
2817            messages(&context, cx),
2818            vec![
2819                (message_1.id, Role::User, 0..2),
2820                (message_2.id, Role::Assistant, 2..4),
2821                (message_3.id, Role::User, 4..4)
2822            ]
2823        );
2824
2825        let message_4 = context.update(cx, |context, cx| {
2826            context
2827                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2828                .unwrap()
2829        });
2830        assert_eq!(
2831            messages(&context, cx),
2832            vec![
2833                (message_1.id, Role::User, 0..2),
2834                (message_2.id, Role::Assistant, 2..4),
2835                (message_4.id, Role::User, 4..5),
2836                (message_3.id, Role::User, 5..5),
2837            ]
2838        );
2839
2840        buffer.update(cx, |buffer, cx| {
2841            buffer.edit([(4..4, "C"), (5..5, "D")], None, cx)
2842        });
2843        assert_eq!(
2844            messages(&context, cx),
2845            vec![
2846                (message_1.id, Role::User, 0..2),
2847                (message_2.id, Role::Assistant, 2..4),
2848                (message_4.id, Role::User, 4..6),
2849                (message_3.id, Role::User, 6..7),
2850            ]
2851        );
2852
2853        // Deleting across message boundaries merges the messages.
2854        buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx));
2855        assert_eq!(
2856            messages(&context, cx),
2857            vec![
2858                (message_1.id, Role::User, 0..3),
2859                (message_3.id, Role::User, 3..4),
2860            ]
2861        );
2862
2863        // Undoing the deletion should also undo the merge.
2864        buffer.update(cx, |buffer, cx| buffer.undo(cx));
2865        assert_eq!(
2866            messages(&context, cx),
2867            vec![
2868                (message_1.id, Role::User, 0..2),
2869                (message_2.id, Role::Assistant, 2..4),
2870                (message_4.id, Role::User, 4..6),
2871                (message_3.id, Role::User, 6..7),
2872            ]
2873        );
2874
2875        // Redoing the deletion should also redo the merge.
2876        buffer.update(cx, |buffer, cx| buffer.redo(cx));
2877        assert_eq!(
2878            messages(&context, cx),
2879            vec![
2880                (message_1.id, Role::User, 0..3),
2881                (message_3.id, Role::User, 3..4),
2882            ]
2883        );
2884
2885        // Ensure we can still insert after a merged message.
2886        let message_5 = context.update(cx, |context, cx| {
2887            context
2888                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
2889                .unwrap()
2890        });
2891        assert_eq!(
2892            messages(&context, cx),
2893            vec![
2894                (message_1.id, Role::User, 0..3),
2895                (message_5.id, Role::System, 3..4),
2896                (message_3.id, Role::User, 4..5)
2897            ]
2898        );
2899    }
2900
2901    #[gpui::test]
2902    fn test_message_splitting(cx: &mut AppContext) {
2903        let settings_store = SettingsStore::test(cx);
2904        cx.set_global(settings_store);
2905        LanguageModelRegistry::test(cx);
2906        assistant_panel::init(cx);
2907        let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2908
2909        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2910        let context =
2911            cx.new_model(|cx| Context::local(registry, None, None, prompt_builder.clone(), cx));
2912        let buffer = context.read(cx).buffer.clone();
2913
2914        let message_1 = context.read(cx).message_anchors[0].clone();
2915        assert_eq!(
2916            messages(&context, cx),
2917            vec![(message_1.id, Role::User, 0..0)]
2918        );
2919
2920        buffer.update(cx, |buffer, cx| {
2921            buffer.edit([(0..0, "aaa\nbbb\nccc\nddd\n")], None, cx)
2922        });
2923
2924        let (_, message_2) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2925        let message_2 = message_2.unwrap();
2926
2927        // We recycle newlines in the middle of a split message
2928        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n");
2929        assert_eq!(
2930            messages(&context, cx),
2931            vec![
2932                (message_1.id, Role::User, 0..4),
2933                (message_2.id, Role::User, 4..16),
2934            ]
2935        );
2936
2937        let (_, message_3) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2938        let message_3 = message_3.unwrap();
2939
2940        // We don't recycle newlines at the end of a split message
2941        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2942        assert_eq!(
2943            messages(&context, cx),
2944            vec![
2945                (message_1.id, Role::User, 0..4),
2946                (message_3.id, Role::User, 4..5),
2947                (message_2.id, Role::User, 5..17),
2948            ]
2949        );
2950
2951        let (_, message_4) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2952        let message_4 = message_4.unwrap();
2953        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2954        assert_eq!(
2955            messages(&context, cx),
2956            vec![
2957                (message_1.id, Role::User, 0..4),
2958                (message_3.id, Role::User, 4..5),
2959                (message_2.id, Role::User, 5..9),
2960                (message_4.id, Role::User, 9..17),
2961            ]
2962        );
2963
2964        let (_, message_5) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2965        let message_5 = message_5.unwrap();
2966        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n");
2967        assert_eq!(
2968            messages(&context, cx),
2969            vec![
2970                (message_1.id, Role::User, 0..4),
2971                (message_3.id, Role::User, 4..5),
2972                (message_2.id, Role::User, 5..9),
2973                (message_4.id, Role::User, 9..10),
2974                (message_5.id, Role::User, 10..18),
2975            ]
2976        );
2977
2978        let (message_6, message_7) =
2979            context.update(cx, |context, cx| context.split_message(14..16, cx));
2980        let message_6 = message_6.unwrap();
2981        let message_7 = message_7.unwrap();
2982        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n");
2983        assert_eq!(
2984            messages(&context, cx),
2985            vec![
2986                (message_1.id, Role::User, 0..4),
2987                (message_3.id, Role::User, 4..5),
2988                (message_2.id, Role::User, 5..9),
2989                (message_4.id, Role::User, 9..10),
2990                (message_5.id, Role::User, 10..14),
2991                (message_6.id, Role::User, 14..17),
2992                (message_7.id, Role::User, 17..19),
2993            ]
2994        );
2995    }
2996
2997    #[gpui::test]
2998    fn test_messages_for_offsets(cx: &mut AppContext) {
2999        let settings_store = SettingsStore::test(cx);
3000        LanguageModelRegistry::test(cx);
3001        cx.set_global(settings_store);
3002        assistant_panel::init(cx);
3003        let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
3004        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3005        let context =
3006            cx.new_model(|cx| Context::local(registry, None, None, prompt_builder.clone(), cx));
3007        let buffer = context.read(cx).buffer.clone();
3008
3009        let message_1 = context.read(cx).message_anchors[0].clone();
3010        assert_eq!(
3011            messages(&context, cx),
3012            vec![(message_1.id, Role::User, 0..0)]
3013        );
3014
3015        buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx));
3016        let message_2 = context
3017            .update(cx, |context, cx| {
3018                context.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx)
3019            })
3020            .unwrap();
3021        buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx));
3022
3023        let message_3 = context
3024            .update(cx, |context, cx| {
3025                context.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3026            })
3027            .unwrap();
3028        buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx));
3029
3030        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc");
3031        assert_eq!(
3032            messages(&context, cx),
3033            vec![
3034                (message_1.id, Role::User, 0..4),
3035                (message_2.id, Role::User, 4..8),
3036                (message_3.id, Role::User, 8..11)
3037            ]
3038        );
3039
3040        assert_eq!(
3041            message_ids_for_offsets(&context, &[0, 4, 9], cx),
3042            [message_1.id, message_2.id, message_3.id]
3043        );
3044        assert_eq!(
3045            message_ids_for_offsets(&context, &[0, 1, 11], cx),
3046            [message_1.id, message_3.id]
3047        );
3048
3049        let message_4 = context
3050            .update(cx, |context, cx| {
3051                context.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx)
3052            })
3053            .unwrap();
3054        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n");
3055        assert_eq!(
3056            messages(&context, cx),
3057            vec![
3058                (message_1.id, Role::User, 0..4),
3059                (message_2.id, Role::User, 4..8),
3060                (message_3.id, Role::User, 8..12),
3061                (message_4.id, Role::User, 12..12)
3062            ]
3063        );
3064        assert_eq!(
3065            message_ids_for_offsets(&context, &[0, 4, 8, 12], cx),
3066            [message_1.id, message_2.id, message_3.id, message_4.id]
3067        );
3068
3069        fn message_ids_for_offsets(
3070            context: &Model<Context>,
3071            offsets: &[usize],
3072            cx: &AppContext,
3073        ) -> Vec<MessageId> {
3074            context
3075                .read(cx)
3076                .messages_for_offsets(offsets.iter().copied(), cx)
3077                .into_iter()
3078                .map(|message| message.id)
3079                .collect()
3080        }
3081    }
3082
3083    #[gpui::test]
3084    async fn test_slash_commands(cx: &mut TestAppContext) {
3085        let settings_store = cx.update(SettingsStore::test);
3086        cx.set_global(settings_store);
3087        cx.update(LanguageModelRegistry::test);
3088        cx.update(Project::init_settings);
3089        cx.update(assistant_panel::init);
3090        let fs = FakeFs::new(cx.background_executor.clone());
3091
3092        fs.insert_tree(
3093            "/test",
3094            json!({
3095                "src": {
3096                    "lib.rs": "fn one() -> usize { 1 }",
3097                    "main.rs": "
3098                        use crate::one;
3099                        fn main() { one(); }
3100                    ".unindent(),
3101                }
3102            }),
3103        )
3104        .await;
3105
3106        let slash_command_registry = cx.update(SlashCommandRegistry::default_global);
3107        slash_command_registry.register_command(file_command::FileSlashCommand, false);
3108
3109        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3110        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3111        let context = cx.new_model(|cx| {
3112            Context::local(registry.clone(), None, None, prompt_builder.clone(), cx)
3113        });
3114
3115        let output_ranges = Rc::new(RefCell::new(HashSet::default()));
3116        context.update(cx, |_, cx| {
3117            cx.subscribe(&context, {
3118                let ranges = output_ranges.clone();
3119                move |_, _, event, _| match event {
3120                    ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
3121                        for range in removed {
3122                            ranges.borrow_mut().remove(range);
3123                        }
3124                        for command in updated {
3125                            ranges.borrow_mut().insert(command.source_range.clone());
3126                        }
3127                    }
3128                    _ => {}
3129                }
3130            })
3131            .detach();
3132        });
3133
3134        let buffer = context.read_with(cx, |context, _| context.buffer.clone());
3135
3136        // Insert a slash command
3137        buffer.update(cx, |buffer, cx| {
3138            buffer.edit([(0..0, "/file src/lib.rs")], None, cx);
3139        });
3140        assert_text_and_output_ranges(
3141            &buffer,
3142            &output_ranges.borrow(),
3143            "
3144            «/file src/lib.rs»
3145            "
3146            .unindent()
3147            .trim_end(),
3148            cx,
3149        );
3150
3151        // Edit the argument of the slash command.
3152        buffer.update(cx, |buffer, cx| {
3153            let edit_offset = buffer.text().find("lib.rs").unwrap();
3154            buffer.edit([(edit_offset..edit_offset + "lib".len(), "main")], None, cx);
3155        });
3156        assert_text_and_output_ranges(
3157            &buffer,
3158            &output_ranges.borrow(),
3159            "
3160            «/file src/main.rs»
3161            "
3162            .unindent()
3163            .trim_end(),
3164            cx,
3165        );
3166
3167        // Edit the name of the slash command, using one that doesn't exist.
3168        buffer.update(cx, |buffer, cx| {
3169            let edit_offset = buffer.text().find("/file").unwrap();
3170            buffer.edit(
3171                [(edit_offset..edit_offset + "/file".len(), "/unknown")],
3172                None,
3173                cx,
3174            );
3175        });
3176        assert_text_and_output_ranges(
3177            &buffer,
3178            &output_ranges.borrow(),
3179            "
3180            /unknown src/main.rs
3181            "
3182            .unindent()
3183            .trim_end(),
3184            cx,
3185        );
3186
3187        #[track_caller]
3188        fn assert_text_and_output_ranges(
3189            buffer: &Model<Buffer>,
3190            ranges: &HashSet<Range<language::Anchor>>,
3191            expected_marked_text: &str,
3192            cx: &mut TestAppContext,
3193        ) {
3194            let (expected_text, expected_ranges) = marked_text_ranges(expected_marked_text, false);
3195            let (actual_text, actual_ranges) = buffer.update(cx, |buffer, _| {
3196                let mut ranges = ranges
3197                    .iter()
3198                    .map(|range| range.to_offset(buffer))
3199                    .collect::<Vec<_>>();
3200                ranges.sort_by_key(|a| a.start);
3201                (buffer.text(), ranges)
3202            });
3203
3204            assert_eq!(actual_text, expected_text);
3205            assert_eq!(actual_ranges, expected_ranges);
3206        }
3207    }
3208
3209    #[gpui::test]
3210    async fn test_edit_step_parsing(cx: &mut TestAppContext) {
3211        cx.update(prompt_library::init);
3212        let settings_store = cx.update(SettingsStore::test);
3213        cx.set_global(settings_store);
3214        cx.update(Project::init_settings);
3215        let fs = FakeFs::new(cx.executor());
3216        fs.as_fake()
3217            .insert_tree(
3218                "/root",
3219                json!({
3220                    "hello.rs": r#"
3221                    fn hello() {
3222                        println!("Hello, World!");
3223                    }
3224                "#.unindent()
3225                }),
3226            )
3227            .await;
3228        let project = Project::test(fs, [Path::new("/root")], cx).await;
3229        cx.update(LanguageModelRegistry::test);
3230
3231        let model = cx.read(|cx| {
3232            LanguageModelRegistry::read_global(cx)
3233                .active_model()
3234                .unwrap()
3235        });
3236        cx.update(assistant_panel::init);
3237        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3238
3239        // Create a new context
3240        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3241        let context = cx.new_model(|cx| {
3242            Context::local(
3243                registry.clone(),
3244                Some(project),
3245                None,
3246                prompt_builder.clone(),
3247                cx,
3248            )
3249        });
3250        let buffer = context.read_with(cx, |context, _| context.buffer.clone());
3251
3252        // Simulate user input
3253        let user_message = indoc! {r#"
3254            Please add unnecessary complexity to this code:
3255
3256            ```hello.rs
3257            fn main() {
3258                println!("Hello, World!");
3259            }
3260            ```
3261        "#};
3262        buffer.update(cx, |buffer, cx| {
3263            buffer.edit([(0..0, user_message)], None, cx);
3264        });
3265
3266        // Simulate LLM response with edit steps
3267        let llm_response = indoc! {r#"
3268            Sure, I can help you with that. Here's a step-by-step process:
3269
3270            <step>
3271            First, let's extract the greeting into a separate function:
3272
3273            ```rust
3274            fn greet() {
3275                println!("Hello, World!");
3276            }
3277
3278            fn main() {
3279                greet();
3280            }
3281            ```
3282            </step>
3283
3284            <step>
3285            Now, let's make the greeting customizable:
3286
3287            ```rust
3288            fn greet(name: &str) {
3289                println!("Hello, {}!", name);
3290            }
3291
3292            fn main() {
3293                greet("World");
3294            }
3295            ```
3296            </step>
3297
3298            These changes make the code more modular and flexible.
3299        "#};
3300
3301        // Simulate the assist method to trigger the LLM response
3302        context.update(cx, |context, cx| context.assist(cx));
3303        cx.run_until_parked();
3304
3305        // Retrieve the assistant response message's start from the context
3306        let response_start_row = context.read_with(cx, |context, cx| {
3307            let buffer = context.buffer.read(cx);
3308            context.message_anchors[1].start.to_point(buffer).row
3309        });
3310
3311        // Simulate the LLM completion
3312        model
3313            .as_fake()
3314            .stream_last_completion_response(llm_response.to_string());
3315        model.as_fake().end_last_completion_stream();
3316
3317        // Wait for the completion to be processed
3318        cx.run_until_parked();
3319
3320        // Verify that the edit steps were parsed correctly
3321        context.read_with(cx, |context, cx| {
3322            assert_eq!(
3323                workflow_steps(context, cx),
3324                vec![
3325                    (
3326                        Point::new(response_start_row + 2, 0)
3327                            ..Point::new(response_start_row + 12, 3),
3328                        WorkflowStepTestStatus::Pending
3329                    ),
3330                    (
3331                        Point::new(response_start_row + 14, 0)
3332                            ..Point::new(response_start_row + 24, 3),
3333                        WorkflowStepTestStatus::Pending
3334                    ),
3335                ]
3336            );
3337        });
3338
3339        model
3340            .as_fake()
3341            .respond_to_last_tool_use(Ok(serde_json::to_value(tool::WorkflowStepResolution {
3342                step_title: "Title".into(),
3343                suggestions: vec![tool::WorkflowSuggestion {
3344                    path: "/root/hello.rs".into(),
3345                    // Simulate a symbol name that's slightly different than our outline query
3346                    kind: tool::WorkflowSuggestionKind::Update {
3347                        symbol: "fn main()".into(),
3348                        description: "Extract a greeting function".into(),
3349                    },
3350                }],
3351            })
3352            .unwrap()));
3353
3354        // Wait for tool use to be processed.
3355        cx.run_until_parked();
3356
3357        // Verify that the first edit step is not pending anymore.
3358        context.read_with(cx, |context, cx| {
3359            assert_eq!(
3360                workflow_steps(context, cx),
3361                vec![
3362                    (
3363                        Point::new(response_start_row + 2, 0)
3364                            ..Point::new(response_start_row + 12, 3),
3365                        WorkflowStepTestStatus::Resolved
3366                    ),
3367                    (
3368                        Point::new(response_start_row + 14, 0)
3369                            ..Point::new(response_start_row + 24, 3),
3370                        WorkflowStepTestStatus::Pending
3371                    ),
3372                ]
3373            );
3374        });
3375
3376        #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3377        enum WorkflowStepTestStatus {
3378            Pending,
3379            Resolved,
3380            Error,
3381        }
3382
3383        fn workflow_steps(
3384            context: &Context,
3385            cx: &AppContext,
3386        ) -> Vec<(Range<Point>, WorkflowStepTestStatus)> {
3387            context
3388                .workflow_steps
3389                .iter()
3390                .map(|step| {
3391                    let buffer = context.buffer.read(cx);
3392                    let status = match &step.status {
3393                        WorkflowStepStatus::Pending(_) => WorkflowStepTestStatus::Pending,
3394                        WorkflowStepStatus::Resolved { .. } => WorkflowStepTestStatus::Resolved,
3395                        WorkflowStepStatus::Error(_) => WorkflowStepTestStatus::Error,
3396                    };
3397                    (step.tagged_range.to_point(buffer), status)
3398                })
3399                .collect()
3400        }
3401    }
3402
3403    #[gpui::test]
3404    async fn test_serialization(cx: &mut TestAppContext) {
3405        let settings_store = cx.update(SettingsStore::test);
3406        cx.set_global(settings_store);
3407        cx.update(LanguageModelRegistry::test);
3408        cx.update(assistant_panel::init);
3409        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3410        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3411        let context = cx.new_model(|cx| {
3412            Context::local(registry.clone(), None, None, prompt_builder.clone(), cx)
3413        });
3414        let buffer = context.read_with(cx, |context, _| context.buffer.clone());
3415        let message_0 = context.read_with(cx, |context, _| context.message_anchors[0].id);
3416        let message_1 = context.update(cx, |context, cx| {
3417            context
3418                .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx)
3419                .unwrap()
3420        });
3421        let message_2 = context.update(cx, |context, cx| {
3422            context
3423                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3424                .unwrap()
3425        });
3426        buffer.update(cx, |buffer, cx| {
3427            buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx);
3428            buffer.finalize_last_transaction();
3429        });
3430        let _message_3 = context.update(cx, |context, cx| {
3431            context
3432                .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx)
3433                .unwrap()
3434        });
3435        buffer.update(cx, |buffer, cx| buffer.undo(cx));
3436        assert_eq!(buffer.read_with(cx, |buffer, _| buffer.text()), "a\nb\nc\n");
3437        assert_eq!(
3438            cx.read(|cx| messages(&context, cx)),
3439            [
3440                (message_0, Role::User, 0..2),
3441                (message_1.id, Role::Assistant, 2..6),
3442                (message_2.id, Role::System, 6..6),
3443            ]
3444        );
3445
3446        let serialized_context = context.read_with(cx, |context, cx| context.serialize(cx));
3447        let deserialized_context = cx.new_model(|cx| {
3448            Context::deserialize(
3449                serialized_context,
3450                Default::default(),
3451                registry.clone(),
3452                prompt_builder.clone(),
3453                None,
3454                None,
3455                cx,
3456            )
3457        });
3458        let deserialized_buffer =
3459            deserialized_context.read_with(cx, |context, _| context.buffer.clone());
3460        assert_eq!(
3461            deserialized_buffer.read_with(cx, |buffer, _| buffer.text()),
3462            "a\nb\nc\n"
3463        );
3464        assert_eq!(
3465            cx.read(|cx| messages(&deserialized_context, cx)),
3466            [
3467                (message_0, Role::User, 0..2),
3468                (message_1.id, Role::Assistant, 2..6),
3469                (message_2.id, Role::System, 6..6),
3470            ]
3471        );
3472    }
3473
3474    #[gpui::test(iterations = 100)]
3475    async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: StdRng) {
3476        let min_peers = env::var("MIN_PEERS")
3477            .map(|i| i.parse().expect("invalid `MIN_PEERS` variable"))
3478            .unwrap_or(2);
3479        let max_peers = env::var("MAX_PEERS")
3480            .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
3481            .unwrap_or(5);
3482        let operations = env::var("OPERATIONS")
3483            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3484            .unwrap_or(50);
3485
3486        let settings_store = cx.update(SettingsStore::test);
3487        cx.set_global(settings_store);
3488        cx.update(LanguageModelRegistry::test);
3489
3490        cx.update(assistant_panel::init);
3491        let slash_commands = cx.update(SlashCommandRegistry::default_global);
3492        slash_commands.register_command(FakeSlashCommand("cmd-1".into()), false);
3493        slash_commands.register_command(FakeSlashCommand("cmd-2".into()), false);
3494        slash_commands.register_command(FakeSlashCommand("cmd-3".into()), false);
3495
3496        let registry = Arc::new(LanguageRegistry::test(cx.background_executor.clone()));
3497        let network = Arc::new(Mutex::new(Network::new(rng.clone())));
3498        let mut contexts = Vec::new();
3499
3500        let num_peers = rng.gen_range(min_peers..=max_peers);
3501        let context_id = ContextId::new();
3502        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3503        for i in 0..num_peers {
3504            let context = cx.new_model(|cx| {
3505                Context::new(
3506                    context_id.clone(),
3507                    i as ReplicaId,
3508                    language::Capability::ReadWrite,
3509                    registry.clone(),
3510                    prompt_builder.clone(),
3511                    None,
3512                    None,
3513                    cx,
3514                )
3515            });
3516
3517            cx.update(|cx| {
3518                cx.subscribe(&context, {
3519                    let network = network.clone();
3520                    move |_, event, _| {
3521                        if let ContextEvent::Operation(op) = event {
3522                            network
3523                                .lock()
3524                                .broadcast(i as ReplicaId, vec![op.to_proto()]);
3525                        }
3526                    }
3527                })
3528                .detach();
3529            });
3530
3531            contexts.push(context);
3532            network.lock().add_peer(i as ReplicaId);
3533        }
3534
3535        let mut mutation_count = operations;
3536
3537        while mutation_count > 0
3538            || !network.lock().is_idle()
3539            || network.lock().contains_disconnected_peers()
3540        {
3541            let context_index = rng.gen_range(0..contexts.len());
3542            let context = &contexts[context_index];
3543
3544            match rng.gen_range(0..100) {
3545                0..=29 if mutation_count > 0 => {
3546                    log::info!("Context {}: edit buffer", context_index);
3547                    context.update(cx, |context, cx| {
3548                        context
3549                            .buffer
3550                            .update(cx, |buffer, cx| buffer.randomly_edit(&mut rng, 1, cx));
3551                    });
3552                    mutation_count -= 1;
3553                }
3554                30..=44 if mutation_count > 0 => {
3555                    context.update(cx, |context, cx| {
3556                        let range = context.buffer.read(cx).random_byte_range(0, &mut rng);
3557                        log::info!("Context {}: split message at {:?}", context_index, range);
3558                        context.split_message(range, cx);
3559                    });
3560                    mutation_count -= 1;
3561                }
3562                45..=59 if mutation_count > 0 => {
3563                    context.update(cx, |context, cx| {
3564                        if let Some(message) = context.messages(cx).choose(&mut rng) {
3565                            let role = *[Role::User, Role::Assistant, Role::System]
3566                                .choose(&mut rng)
3567                                .unwrap();
3568                            log::info!(
3569                                "Context {}: insert message after {:?} with {:?}",
3570                                context_index,
3571                                message.id,
3572                                role
3573                            );
3574                            context.insert_message_after(message.id, role, MessageStatus::Done, cx);
3575                        }
3576                    });
3577                    mutation_count -= 1;
3578                }
3579                60..=74 if mutation_count > 0 => {
3580                    context.update(cx, |context, cx| {
3581                        let command_text = "/".to_string()
3582                            + slash_commands
3583                                .command_names()
3584                                .choose(&mut rng)
3585                                .unwrap()
3586                                .clone()
3587                                .as_ref();
3588
3589                        let command_range = context.buffer.update(cx, |buffer, cx| {
3590                            let offset = buffer.random_byte_range(0, &mut rng).start;
3591                            buffer.edit(
3592                                [(offset..offset, format!("\n{}\n", command_text))],
3593                                None,
3594                                cx,
3595                            );
3596                            offset + 1..offset + 1 + command_text.len()
3597                        });
3598
3599                        let output_len = rng.gen_range(1..=10);
3600                        let output_text = RandomCharIter::new(&mut rng)
3601                            .filter(|c| *c != '\r')
3602                            .take(output_len)
3603                            .collect::<String>();
3604
3605                        let num_sections = rng.gen_range(0..=3);
3606                        let mut sections = Vec::with_capacity(num_sections);
3607                        for _ in 0..num_sections {
3608                            let section_start = rng.gen_range(0..output_len);
3609                            let section_end = rng.gen_range(section_start..=output_len);
3610                            sections.push(SlashCommandOutputSection {
3611                                range: section_start..section_end,
3612                                icon: ui::IconName::Ai,
3613                                label: "section".into(),
3614                            });
3615                        }
3616
3617                        log::info!(
3618                            "Context {}: insert slash command output at {:?} with {:?}",
3619                            context_index,
3620                            command_range,
3621                            sections
3622                        );
3623
3624                        let command_range =
3625                            context.buffer.read(cx).anchor_after(command_range.start)
3626                                ..context.buffer.read(cx).anchor_after(command_range.end);
3627                        context.insert_command_output(
3628                            command_range,
3629                            Task::ready(Ok(SlashCommandOutput {
3630                                text: output_text,
3631                                sections,
3632                                run_commands_in_text: false,
3633                            })),
3634                            true,
3635                            cx,
3636                        );
3637                    });
3638                    cx.run_until_parked();
3639                    mutation_count -= 1;
3640                }
3641                75..=84 if mutation_count > 0 => {
3642                    context.update(cx, |context, cx| {
3643                        if let Some(message) = context.messages(cx).choose(&mut rng) {
3644                            let new_status = match rng.gen_range(0..3) {
3645                                0 => MessageStatus::Done,
3646                                1 => MessageStatus::Pending,
3647                                _ => MessageStatus::Error(SharedString::from("Random error")),
3648                            };
3649                            log::info!(
3650                                "Context {}: update message {:?} status to {:?}",
3651                                context_index,
3652                                message.id,
3653                                new_status
3654                            );
3655                            context.update_metadata(message.id, cx, |metadata| {
3656                                metadata.status = new_status;
3657                            });
3658                        }
3659                    });
3660                    mutation_count -= 1;
3661                }
3662                _ => {
3663                    let replica_id = context_index as ReplicaId;
3664                    if network.lock().is_disconnected(replica_id) {
3665                        network.lock().reconnect_peer(replica_id, 0);
3666
3667                        let (ops_to_send, ops_to_receive) = cx.read(|cx| {
3668                            let host_context = &contexts[0].read(cx);
3669                            let guest_context = context.read(cx);
3670                            (
3671                                guest_context.serialize_ops(&host_context.version(cx), cx),
3672                                host_context.serialize_ops(&guest_context.version(cx), cx),
3673                            )
3674                        });
3675                        let ops_to_send = ops_to_send.await;
3676                        let ops_to_receive = ops_to_receive
3677                            .await
3678                            .into_iter()
3679                            .map(ContextOperation::from_proto)
3680                            .collect::<Result<Vec<_>>>()
3681                            .unwrap();
3682                        log::info!(
3683                            "Context {}: reconnecting. Sent {} operations, received {} operations",
3684                            context_index,
3685                            ops_to_send.len(),
3686                            ops_to_receive.len()
3687                        );
3688
3689                        network.lock().broadcast(replica_id, ops_to_send);
3690                        context
3691                            .update(cx, |context, cx| context.apply_ops(ops_to_receive, cx))
3692                            .unwrap();
3693                    } else if rng.gen_bool(0.1) && replica_id != 0 {
3694                        log::info!("Context {}: disconnecting", context_index);
3695                        network.lock().disconnect_peer(replica_id);
3696                    } else if network.lock().has_unreceived(replica_id) {
3697                        log::info!("Context {}: applying operations", context_index);
3698                        let ops = network.lock().receive(replica_id);
3699                        let ops = ops
3700                            .into_iter()
3701                            .map(ContextOperation::from_proto)
3702                            .collect::<Result<Vec<_>>>()
3703                            .unwrap();
3704                        context
3705                            .update(cx, |context, cx| context.apply_ops(ops, cx))
3706                            .unwrap();
3707                    }
3708                }
3709            }
3710        }
3711
3712        cx.read(|cx| {
3713            let first_context = contexts[0].read(cx);
3714            for context in &contexts[1..] {
3715                let context = context.read(cx);
3716                assert!(context.pending_ops.is_empty());
3717                assert_eq!(
3718                    context.buffer.read(cx).text(),
3719                    first_context.buffer.read(cx).text(),
3720                    "Context {} text != Context 0 text",
3721                    context.buffer.read(cx).replica_id()
3722                );
3723                assert_eq!(
3724                    context.message_anchors,
3725                    first_context.message_anchors,
3726                    "Context {} messages != Context 0 messages",
3727                    context.buffer.read(cx).replica_id()
3728                );
3729                assert_eq!(
3730                    context.messages_metadata,
3731                    first_context.messages_metadata,
3732                    "Context {} message metadata != Context 0 message metadata",
3733                    context.buffer.read(cx).replica_id()
3734                );
3735                assert_eq!(
3736                    context.slash_command_output_sections,
3737                    first_context.slash_command_output_sections,
3738                    "Context {} slash command output sections != Context 0 slash command output sections",
3739                    context.buffer.read(cx).replica_id()
3740                );
3741            }
3742        });
3743    }
3744
3745    fn messages(context: &Model<Context>, cx: &AppContext) -> Vec<(MessageId, Role, Range<usize>)> {
3746        context
3747            .read(cx)
3748            .messages(cx)
3749            .map(|message| (message.id, message.role, message.offset_range))
3750            .collect()
3751    }
3752
3753    #[derive(Clone)]
3754    struct FakeSlashCommand(String);
3755
3756    impl SlashCommand for FakeSlashCommand {
3757        fn name(&self) -> String {
3758            self.0.clone()
3759        }
3760
3761        fn description(&self) -> String {
3762            format!("Fake slash command: {}", self.0)
3763        }
3764
3765        fn menu_text(&self) -> String {
3766            format!("Run fake command: {}", self.0)
3767        }
3768
3769        fn complete_argument(
3770            self: Arc<Self>,
3771            _arguments: &[String],
3772            _cancel: Arc<AtomicBool>,
3773            _workspace: Option<WeakView<Workspace>>,
3774            _cx: &mut WindowContext,
3775        ) -> Task<Result<Vec<ArgumentCompletion>>> {
3776            Task::ready(Ok(vec![]))
3777        }
3778
3779        fn requires_argument(&self) -> bool {
3780            false
3781        }
3782
3783        fn run(
3784            self: Arc<Self>,
3785            _arguments: &[String],
3786            _workspace: WeakView<Workspace>,
3787            _delegate: Option<Arc<dyn LspAdapterDelegate>>,
3788            _cx: &mut WindowContext,
3789        ) -> Task<Result<SlashCommandOutput>> {
3790            Task::ready(Ok(SlashCommandOutput {
3791                text: format!("Executed fake command: {}", self.0),
3792                sections: vec![],
3793                run_commands_in_text: false,
3794            }))
3795        }
3796    }
3797}
3798
3799mod tool {
3800    use gpui::AsyncAppContext;
3801
3802    use super::*;
3803
3804    #[derive(Debug, Serialize, Deserialize, JsonSchema)]
3805    pub struct WorkflowStepResolution {
3806        /// An extremely short title for the edit step represented by these operations.
3807        pub step_title: String,
3808        /// A sequence of operations to apply to the codebase.
3809        /// When multiple operations are required for a step, be sure to include multiple operations in this list.
3810        pub suggestions: Vec<WorkflowSuggestion>,
3811    }
3812
3813    impl LanguageModelTool for WorkflowStepResolution {
3814        fn name() -> String {
3815            "edit".into()
3816        }
3817
3818        fn description() -> String {
3819            "suggest edits to one or more locations in the codebase".into()
3820        }
3821    }
3822
3823    /// A description of an operation to apply to one location in the codebase.
3824    ///
3825    /// This object represents a single edit operation that can be performed on a specific file
3826    /// in the codebase. It encapsulates both the location (file path) and the nature of the
3827    /// edit to be made.
3828    ///
3829    /// # Fields
3830    ///
3831    /// * `path`: A string representing the file path where the edit operation should be applied.
3832    ///           This path is relative to the root of the project or repository.
3833    ///
3834    /// * `kind`: An enum representing the specific type of edit operation to be performed.
3835    ///
3836    /// # Usage
3837    ///
3838    /// `EditOperation` is used within a code editor to represent and apply
3839    /// programmatic changes to source code. It provides a structured way to describe
3840    /// edits for features like refactoring tools or AI-assisted coding suggestions.
3841    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
3842    pub struct WorkflowSuggestion {
3843        /// The path to the file containing the relevant operation
3844        pub path: String,
3845        #[serde(flatten)]
3846        pub kind: WorkflowSuggestionKind,
3847    }
3848
3849    impl WorkflowSuggestion {
3850        pub(super) async fn resolve(
3851            &self,
3852            project: Model<Project>,
3853            mut cx: AsyncAppContext,
3854        ) -> Result<(Model<Buffer>, super::WorkflowSuggestion)> {
3855            let path = self.path.clone();
3856            let kind = self.kind.clone();
3857            let buffer = project
3858                .update(&mut cx, |project, cx| {
3859                    let project_path = project
3860                        .find_project_path(Path::new(&path), cx)
3861                        .with_context(|| format!("worktree not found for {:?}", path))?;
3862                    anyhow::Ok(project.open_buffer(project_path, cx))
3863                })??
3864                .await?;
3865
3866            let mut parse_status = buffer.read_with(&cx, |buffer, _cx| buffer.parse_status())?;
3867            while *parse_status.borrow() != ParseStatus::Idle {
3868                parse_status.changed().await?;
3869            }
3870
3871            let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
3872            let outline = snapshot.outline(None).context("no outline for buffer")?;
3873
3874            let suggestion;
3875            match kind {
3876                WorkflowSuggestionKind::Update {
3877                    symbol,
3878                    description,
3879                } => {
3880                    let symbol = outline
3881                        .find_most_similar(&symbol)
3882                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3883                        .to_point(&snapshot);
3884                    let start = symbol
3885                        .annotation_range
3886                        .map_or(symbol.range.start, |range| range.start);
3887                    let start = Point::new(start.row, 0);
3888                    let end = Point::new(
3889                        symbol.range.end.row,
3890                        snapshot.line_len(symbol.range.end.row),
3891                    );
3892                    let range = snapshot.anchor_before(start)..snapshot.anchor_after(end);
3893                    suggestion = super::WorkflowSuggestion::Update { range, description };
3894                }
3895                WorkflowSuggestionKind::Create { description } => {
3896                    suggestion = super::WorkflowSuggestion::CreateFile { description };
3897                }
3898                WorkflowSuggestionKind::InsertSiblingBefore {
3899                    symbol,
3900                    description,
3901                } => {
3902                    let symbol = outline
3903                        .find_most_similar(&symbol)
3904                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3905                        .to_point(&snapshot);
3906                    let position = snapshot.anchor_before(
3907                        symbol
3908                            .annotation_range
3909                            .map_or(symbol.range.start, |annotation_range| {
3910                                annotation_range.start
3911                            }),
3912                    );
3913                    suggestion = super::WorkflowSuggestion::InsertSiblingBefore {
3914                        position,
3915                        description,
3916                    };
3917                }
3918                WorkflowSuggestionKind::InsertSiblingAfter {
3919                    symbol,
3920                    description,
3921                } => {
3922                    let symbol = outline
3923                        .find_most_similar(&symbol)
3924                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3925                        .to_point(&snapshot);
3926                    let position = snapshot.anchor_after(symbol.range.end);
3927                    suggestion = super::WorkflowSuggestion::InsertSiblingAfter {
3928                        position,
3929                        description,
3930                    };
3931                }
3932                WorkflowSuggestionKind::PrependChild {
3933                    symbol,
3934                    description,
3935                } => {
3936                    if let Some(symbol) = symbol {
3937                        let symbol = outline
3938                            .find_most_similar(&symbol)
3939                            .with_context(|| format!("symbol not found: {:?}", symbol))?
3940                            .to_point(&snapshot);
3941
3942                        let position = snapshot.anchor_after(
3943                            symbol
3944                                .body_range
3945                                .map_or(symbol.range.start, |body_range| body_range.start),
3946                        );
3947                        suggestion = super::WorkflowSuggestion::PrependChild {
3948                            position,
3949                            description,
3950                        };
3951                    } else {
3952                        suggestion = super::WorkflowSuggestion::PrependChild {
3953                            position: language::Anchor::MIN,
3954                            description,
3955                        };
3956                    }
3957                }
3958                WorkflowSuggestionKind::AppendChild {
3959                    symbol,
3960                    description,
3961                } => {
3962                    if let Some(symbol) = symbol {
3963                        let symbol = outline
3964                            .find_most_similar(&symbol)
3965                            .with_context(|| format!("symbol not found: {:?}", symbol))?
3966                            .to_point(&snapshot);
3967
3968                        let position = snapshot.anchor_before(
3969                            symbol
3970                                .body_range
3971                                .map_or(symbol.range.end, |body_range| body_range.end),
3972                        );
3973                        suggestion = super::WorkflowSuggestion::AppendChild {
3974                            position,
3975                            description,
3976                        };
3977                    } else {
3978                        suggestion = super::WorkflowSuggestion::PrependChild {
3979                            position: language::Anchor::MAX,
3980                            description,
3981                        };
3982                    }
3983                }
3984                WorkflowSuggestionKind::Delete { symbol } => {
3985                    let symbol = outline
3986                        .find_most_similar(&symbol)
3987                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3988                        .to_point(&snapshot);
3989                    let start = symbol
3990                        .annotation_range
3991                        .map_or(symbol.range.start, |range| range.start);
3992                    let start = Point::new(start.row, 0);
3993                    let end = Point::new(
3994                        symbol.range.end.row,
3995                        snapshot.line_len(symbol.range.end.row),
3996                    );
3997                    let range = snapshot.anchor_before(start)..snapshot.anchor_after(end);
3998                    suggestion = super::WorkflowSuggestion::Delete { range };
3999                }
4000            }
4001
4002            Ok((buffer, suggestion))
4003        }
4004    }
4005
4006    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
4007    #[serde(tag = "kind")]
4008    pub enum WorkflowSuggestionKind {
4009        /// Rewrites the specified symbol entirely based on the given description.
4010        /// This operation completely replaces the existing symbol with new content.
4011        Update {
4012            /// A fully-qualified reference to the symbol, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
4013            /// The path should uniquely identify the symbol within the containing file.
4014            symbol: String,
4015            /// A brief description of the transformation to apply to the symbol.
4016            description: String,
4017        },
4018        /// Creates a new file with the given path based on the provided description.
4019        /// This operation adds a new file to the codebase.
4020        Create {
4021            /// A brief description of the file to be created.
4022            description: String,
4023        },
4024        /// Inserts a new symbol based on the given description before the specified symbol.
4025        /// This operation adds new content immediately preceding an existing symbol.
4026        InsertSiblingBefore {
4027            /// A fully-qualified reference to the symbol, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
4028            /// The new content will be inserted immediately before this symbol.
4029            symbol: String,
4030            /// A brief description of the new symbol to be inserted.
4031            description: String,
4032        },
4033        /// Inserts a new symbol based on the given description after the specified symbol.
4034        /// This operation adds new content immediately following an existing symbol.
4035        InsertSiblingAfter {
4036            /// A fully-qualified reference to the symbol, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
4037            /// The new content will be inserted immediately after this symbol.
4038            symbol: String,
4039            /// A brief description of the new symbol to be inserted.
4040            description: String,
4041        },
4042        /// Inserts a new symbol as a child of the specified symbol at the start.
4043        /// This operation adds new content as the first child of an existing symbol (or file if no symbol is provided).
4044        PrependChild {
4045            /// An optional fully-qualified reference to the symbol after the code you want to insert, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
4046            /// If provided, the new content will be inserted as the first child of this symbol.
4047            /// If not provided, the new content will be inserted at the top of the file.
4048            symbol: Option<String>,
4049            /// A brief description of the new symbol to be inserted.
4050            description: String,
4051        },
4052        /// Inserts a new symbol as a child of the specified symbol at the end.
4053        /// This operation adds new content as the last child of an existing symbol (or file if no symbol is provided).
4054        AppendChild {
4055            /// An optional fully-qualified reference to the symbol before the code you want to insert, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
4056            /// If provided, the new content will be inserted as the last child of this symbol.
4057            /// If not provided, the new content will be applied at the bottom of the file.
4058            symbol: Option<String>,
4059            /// A brief description of the new symbol to be inserted.
4060            description: String,
4061        },
4062        /// Deletes the specified symbol from the containing file.
4063        Delete {
4064            /// An fully-qualified reference to the symbol to be deleted, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
4065            symbol: String,
4066        },
4067    }
4068
4069    impl WorkflowSuggestionKind {
4070        pub fn symbol(&self) -> Option<&str> {
4071            match self {
4072                Self::Update { symbol, .. } => Some(symbol),
4073                Self::InsertSiblingBefore { symbol, .. } => Some(symbol),
4074                Self::InsertSiblingAfter { symbol, .. } => Some(symbol),
4075                Self::PrependChild { symbol, .. } => symbol.as_deref(),
4076                Self::AppendChild { symbol, .. } => symbol.as_deref(),
4077                Self::Delete { symbol } => Some(symbol),
4078                Self::Create { .. } => None,
4079            }
4080        }
4081
4082        pub fn description(&self) -> Option<&str> {
4083            match self {
4084                Self::Update { description, .. } => Some(description),
4085                Self::Create { description } => Some(description),
4086                Self::InsertSiblingBefore { description, .. } => Some(description),
4087                Self::InsertSiblingAfter { description, .. } => Some(description),
4088                Self::PrependChild { description, .. } => Some(description),
4089                Self::AppendChild { description, .. } => Some(description),
4090                Self::Delete { .. } => None,
4091            }
4092        }
4093
4094        pub fn initial_insertion(&self) -> Option<InitialInsertion> {
4095            match self {
4096                WorkflowSuggestionKind::InsertSiblingBefore { .. } => {
4097                    Some(InitialInsertion::NewlineAfter)
4098                }
4099                WorkflowSuggestionKind::InsertSiblingAfter { .. } => {
4100                    Some(InitialInsertion::NewlineBefore)
4101                }
4102                WorkflowSuggestionKind::PrependChild { .. } => Some(InitialInsertion::NewlineAfter),
4103                WorkflowSuggestionKind::AppendChild { .. } => Some(InitialInsertion::NewlineBefore),
4104                _ => None,
4105            }
4106        }
4107    }
4108}