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