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::{
2526        assistant_panel, prompt_library,
2527        slash_command::{active_command, file_command},
2528        MessageId,
2529    };
2530    use assistant_slash_command::{ArgumentCompletion, SlashCommand};
2531    use fs::FakeFs;
2532    use gpui::{AppContext, TestAppContext, WeakView};
2533    use indoc::indoc;
2534    use language::LspAdapterDelegate;
2535    use parking_lot::Mutex;
2536    use project::Project;
2537    use rand::prelude::*;
2538    use serde_json::json;
2539    use settings::SettingsStore;
2540    use std::{cell::RefCell, env, rc::Rc, sync::atomic::AtomicBool};
2541    use text::{network::Network, ToPoint};
2542    use ui::WindowContext;
2543    use unindent::Unindent;
2544    use util::{test::marked_text_ranges, RandomCharIter};
2545    use workspace::Workspace;
2546
2547    #[gpui::test]
2548    fn test_inserting_and_removing_messages(cx: &mut AppContext) {
2549        let settings_store = SettingsStore::test(cx);
2550        LanguageModelRegistry::test(cx);
2551        cx.set_global(settings_store);
2552        assistant_panel::init(cx);
2553        let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2554        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2555        let context =
2556            cx.new_model(|cx| Context::local(registry, None, None, prompt_builder.clone(), cx));
2557        let buffer = context.read(cx).buffer.clone();
2558
2559        let message_1 = context.read(cx).message_anchors[0].clone();
2560        assert_eq!(
2561            messages(&context, cx),
2562            vec![(message_1.id, Role::User, 0..0)]
2563        );
2564
2565        let message_2 = context.update(cx, |context, cx| {
2566            context
2567                .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx)
2568                .unwrap()
2569        });
2570        assert_eq!(
2571            messages(&context, cx),
2572            vec![
2573                (message_1.id, Role::User, 0..1),
2574                (message_2.id, Role::Assistant, 1..1)
2575            ]
2576        );
2577
2578        buffer.update(cx, |buffer, cx| {
2579            buffer.edit([(0..0, "1"), (1..1, "2")], None, cx)
2580        });
2581        assert_eq!(
2582            messages(&context, cx),
2583            vec![
2584                (message_1.id, Role::User, 0..2),
2585                (message_2.id, Role::Assistant, 2..3)
2586            ]
2587        );
2588
2589        let message_3 = context.update(cx, |context, cx| {
2590            context
2591                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2592                .unwrap()
2593        });
2594        assert_eq!(
2595            messages(&context, cx),
2596            vec![
2597                (message_1.id, Role::User, 0..2),
2598                (message_2.id, Role::Assistant, 2..4),
2599                (message_3.id, Role::User, 4..4)
2600            ]
2601        );
2602
2603        let message_4 = context.update(cx, |context, cx| {
2604            context
2605                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2606                .unwrap()
2607        });
2608        assert_eq!(
2609            messages(&context, cx),
2610            vec![
2611                (message_1.id, Role::User, 0..2),
2612                (message_2.id, Role::Assistant, 2..4),
2613                (message_4.id, Role::User, 4..5),
2614                (message_3.id, Role::User, 5..5),
2615            ]
2616        );
2617
2618        buffer.update(cx, |buffer, cx| {
2619            buffer.edit([(4..4, "C"), (5..5, "D")], None, cx)
2620        });
2621        assert_eq!(
2622            messages(&context, cx),
2623            vec![
2624                (message_1.id, Role::User, 0..2),
2625                (message_2.id, Role::Assistant, 2..4),
2626                (message_4.id, Role::User, 4..6),
2627                (message_3.id, Role::User, 6..7),
2628            ]
2629        );
2630
2631        // Deleting across message boundaries merges the messages.
2632        buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx));
2633        assert_eq!(
2634            messages(&context, cx),
2635            vec![
2636                (message_1.id, Role::User, 0..3),
2637                (message_3.id, Role::User, 3..4),
2638            ]
2639        );
2640
2641        // Undoing the deletion should also undo the merge.
2642        buffer.update(cx, |buffer, cx| buffer.undo(cx));
2643        assert_eq!(
2644            messages(&context, cx),
2645            vec![
2646                (message_1.id, Role::User, 0..2),
2647                (message_2.id, Role::Assistant, 2..4),
2648                (message_4.id, Role::User, 4..6),
2649                (message_3.id, Role::User, 6..7),
2650            ]
2651        );
2652
2653        // Redoing the deletion should also redo the merge.
2654        buffer.update(cx, |buffer, cx| buffer.redo(cx));
2655        assert_eq!(
2656            messages(&context, cx),
2657            vec![
2658                (message_1.id, Role::User, 0..3),
2659                (message_3.id, Role::User, 3..4),
2660            ]
2661        );
2662
2663        // Ensure we can still insert after a merged message.
2664        let message_5 = context.update(cx, |context, cx| {
2665            context
2666                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
2667                .unwrap()
2668        });
2669        assert_eq!(
2670            messages(&context, cx),
2671            vec![
2672                (message_1.id, Role::User, 0..3),
2673                (message_5.id, Role::System, 3..4),
2674                (message_3.id, Role::User, 4..5)
2675            ]
2676        );
2677    }
2678
2679    #[gpui::test]
2680    fn test_message_splitting(cx: &mut AppContext) {
2681        let settings_store = SettingsStore::test(cx);
2682        cx.set_global(settings_store);
2683        LanguageModelRegistry::test(cx);
2684        assistant_panel::init(cx);
2685        let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2686
2687        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2688        let context =
2689            cx.new_model(|cx| Context::local(registry, None, None, prompt_builder.clone(), cx));
2690        let buffer = context.read(cx).buffer.clone();
2691
2692        let message_1 = context.read(cx).message_anchors[0].clone();
2693        assert_eq!(
2694            messages(&context, cx),
2695            vec![(message_1.id, Role::User, 0..0)]
2696        );
2697
2698        buffer.update(cx, |buffer, cx| {
2699            buffer.edit([(0..0, "aaa\nbbb\nccc\nddd\n")], None, cx)
2700        });
2701
2702        let (_, message_2) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2703        let message_2 = message_2.unwrap();
2704
2705        // We recycle newlines in the middle of a split message
2706        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n");
2707        assert_eq!(
2708            messages(&context, cx),
2709            vec![
2710                (message_1.id, Role::User, 0..4),
2711                (message_2.id, Role::User, 4..16),
2712            ]
2713        );
2714
2715        let (_, message_3) = context.update(cx, |context, cx| context.split_message(3..3, cx));
2716        let message_3 = message_3.unwrap();
2717
2718        // We don't recycle newlines at the end of a split message
2719        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2720        assert_eq!(
2721            messages(&context, cx),
2722            vec![
2723                (message_1.id, Role::User, 0..4),
2724                (message_3.id, Role::User, 4..5),
2725                (message_2.id, Role::User, 5..17),
2726            ]
2727        );
2728
2729        let (_, message_4) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2730        let message_4 = message_4.unwrap();
2731        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
2732        assert_eq!(
2733            messages(&context, cx),
2734            vec![
2735                (message_1.id, Role::User, 0..4),
2736                (message_3.id, Role::User, 4..5),
2737                (message_2.id, Role::User, 5..9),
2738                (message_4.id, Role::User, 9..17),
2739            ]
2740        );
2741
2742        let (_, message_5) = context.update(cx, |context, cx| context.split_message(9..9, cx));
2743        let message_5 = message_5.unwrap();
2744        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n");
2745        assert_eq!(
2746            messages(&context, cx),
2747            vec![
2748                (message_1.id, Role::User, 0..4),
2749                (message_3.id, Role::User, 4..5),
2750                (message_2.id, Role::User, 5..9),
2751                (message_4.id, Role::User, 9..10),
2752                (message_5.id, Role::User, 10..18),
2753            ]
2754        );
2755
2756        let (message_6, message_7) =
2757            context.update(cx, |context, cx| context.split_message(14..16, cx));
2758        let message_6 = message_6.unwrap();
2759        let message_7 = message_7.unwrap();
2760        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n");
2761        assert_eq!(
2762            messages(&context, cx),
2763            vec![
2764                (message_1.id, Role::User, 0..4),
2765                (message_3.id, Role::User, 4..5),
2766                (message_2.id, Role::User, 5..9),
2767                (message_4.id, Role::User, 9..10),
2768                (message_5.id, Role::User, 10..14),
2769                (message_6.id, Role::User, 14..17),
2770                (message_7.id, Role::User, 17..19),
2771            ]
2772        );
2773    }
2774
2775    #[gpui::test]
2776    fn test_messages_for_offsets(cx: &mut AppContext) {
2777        let settings_store = SettingsStore::test(cx);
2778        LanguageModelRegistry::test(cx);
2779        cx.set_global(settings_store);
2780        assistant_panel::init(cx);
2781        let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
2782        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2783        let context =
2784            cx.new_model(|cx| Context::local(registry, None, None, prompt_builder.clone(), cx));
2785        let buffer = context.read(cx).buffer.clone();
2786
2787        let message_1 = context.read(cx).message_anchors[0].clone();
2788        assert_eq!(
2789            messages(&context, cx),
2790            vec![(message_1.id, Role::User, 0..0)]
2791        );
2792
2793        buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx));
2794        let message_2 = context
2795            .update(cx, |context, cx| {
2796                context.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx)
2797            })
2798            .unwrap();
2799        buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx));
2800
2801        let message_3 = context
2802            .update(cx, |context, cx| {
2803                context.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
2804            })
2805            .unwrap();
2806        buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx));
2807
2808        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc");
2809        assert_eq!(
2810            messages(&context, cx),
2811            vec![
2812                (message_1.id, Role::User, 0..4),
2813                (message_2.id, Role::User, 4..8),
2814                (message_3.id, Role::User, 8..11)
2815            ]
2816        );
2817
2818        assert_eq!(
2819            message_ids_for_offsets(&context, &[0, 4, 9], cx),
2820            [message_1.id, message_2.id, message_3.id]
2821        );
2822        assert_eq!(
2823            message_ids_for_offsets(&context, &[0, 1, 11], cx),
2824            [message_1.id, message_3.id]
2825        );
2826
2827        let message_4 = context
2828            .update(cx, |context, cx| {
2829                context.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx)
2830            })
2831            .unwrap();
2832        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n");
2833        assert_eq!(
2834            messages(&context, cx),
2835            vec![
2836                (message_1.id, Role::User, 0..4),
2837                (message_2.id, Role::User, 4..8),
2838                (message_3.id, Role::User, 8..12),
2839                (message_4.id, Role::User, 12..12)
2840            ]
2841        );
2842        assert_eq!(
2843            message_ids_for_offsets(&context, &[0, 4, 8, 12], cx),
2844            [message_1.id, message_2.id, message_3.id, message_4.id]
2845        );
2846
2847        fn message_ids_for_offsets(
2848            context: &Model<Context>,
2849            offsets: &[usize],
2850            cx: &AppContext,
2851        ) -> Vec<MessageId> {
2852            context
2853                .read(cx)
2854                .messages_for_offsets(offsets.iter().copied(), cx)
2855                .into_iter()
2856                .map(|message| message.id)
2857                .collect()
2858        }
2859    }
2860
2861    #[gpui::test]
2862    async fn test_slash_commands(cx: &mut TestAppContext) {
2863        let settings_store = cx.update(SettingsStore::test);
2864        cx.set_global(settings_store);
2865        cx.update(LanguageModelRegistry::test);
2866        cx.update(Project::init_settings);
2867        cx.update(assistant_panel::init);
2868        let fs = FakeFs::new(cx.background_executor.clone());
2869
2870        fs.insert_tree(
2871            "/test",
2872            json!({
2873                "src": {
2874                    "lib.rs": "fn one() -> usize { 1 }",
2875                    "main.rs": "
2876                        use crate::one;
2877                        fn main() { one(); }
2878                    ".unindent(),
2879                }
2880            }),
2881        )
2882        .await;
2883
2884        let slash_command_registry = cx.update(SlashCommandRegistry::default_global);
2885        slash_command_registry.register_command(file_command::FileSlashCommand, false);
2886        slash_command_registry.register_command(active_command::ActiveSlashCommand, false);
2887
2888        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
2889        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2890        let context = cx.new_model(|cx| {
2891            Context::local(registry.clone(), None, None, prompt_builder.clone(), cx)
2892        });
2893
2894        let output_ranges = Rc::new(RefCell::new(HashSet::default()));
2895        context.update(cx, |_, cx| {
2896            cx.subscribe(&context, {
2897                let ranges = output_ranges.clone();
2898                move |_, _, event, _| match event {
2899                    ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
2900                        for range in removed {
2901                            ranges.borrow_mut().remove(range);
2902                        }
2903                        for command in updated {
2904                            ranges.borrow_mut().insert(command.source_range.clone());
2905                        }
2906                    }
2907                    _ => {}
2908                }
2909            })
2910            .detach();
2911        });
2912
2913        let buffer = context.read_with(cx, |context, _| context.buffer.clone());
2914
2915        // Insert a slash command
2916        buffer.update(cx, |buffer, cx| {
2917            buffer.edit([(0..0, "/file src/lib.rs")], None, cx);
2918        });
2919        assert_text_and_output_ranges(
2920            &buffer,
2921            &output_ranges.borrow(),
2922            "
2923            «/file src/lib.rs»
2924            "
2925            .unindent()
2926            .trim_end(),
2927            cx,
2928        );
2929
2930        // Edit the argument of the slash command.
2931        buffer.update(cx, |buffer, cx| {
2932            let edit_offset = buffer.text().find("lib.rs").unwrap();
2933            buffer.edit([(edit_offset..edit_offset + "lib".len(), "main")], None, cx);
2934        });
2935        assert_text_and_output_ranges(
2936            &buffer,
2937            &output_ranges.borrow(),
2938            "
2939            «/file src/main.rs»
2940            "
2941            .unindent()
2942            .trim_end(),
2943            cx,
2944        );
2945
2946        // Edit the name of the slash command, using one that doesn't exist.
2947        buffer.update(cx, |buffer, cx| {
2948            let edit_offset = buffer.text().find("/file").unwrap();
2949            buffer.edit(
2950                [(edit_offset..edit_offset + "/file".len(), "/unknown")],
2951                None,
2952                cx,
2953            );
2954        });
2955        assert_text_and_output_ranges(
2956            &buffer,
2957            &output_ranges.borrow(),
2958            "
2959            /unknown src/main.rs
2960            "
2961            .unindent()
2962            .trim_end(),
2963            cx,
2964        );
2965
2966        #[track_caller]
2967        fn assert_text_and_output_ranges(
2968            buffer: &Model<Buffer>,
2969            ranges: &HashSet<Range<language::Anchor>>,
2970            expected_marked_text: &str,
2971            cx: &mut TestAppContext,
2972        ) {
2973            let (expected_text, expected_ranges) = marked_text_ranges(expected_marked_text, false);
2974            let (actual_text, actual_ranges) = buffer.update(cx, |buffer, _| {
2975                let mut ranges = ranges
2976                    .iter()
2977                    .map(|range| range.to_offset(buffer))
2978                    .collect::<Vec<_>>();
2979                ranges.sort_by_key(|a| a.start);
2980                (buffer.text(), ranges)
2981            });
2982
2983            assert_eq!(actual_text, expected_text);
2984            assert_eq!(actual_ranges, expected_ranges);
2985        }
2986    }
2987
2988    #[gpui::test]
2989    async fn test_edit_step_parsing(cx: &mut TestAppContext) {
2990        cx.update(prompt_library::init);
2991        let settings_store = cx.update(SettingsStore::test);
2992        cx.set_global(settings_store);
2993        cx.update(Project::init_settings);
2994        let fs = FakeFs::new(cx.executor());
2995        fs.as_fake()
2996            .insert_tree(
2997                "/root",
2998                json!({
2999                    "hello.rs": r#"
3000                    fn hello() {
3001                        println!("Hello, World!");
3002                    }
3003                "#.unindent()
3004                }),
3005            )
3006            .await;
3007        let project = Project::test(fs, [Path::new("/root")], cx).await;
3008        cx.update(LanguageModelRegistry::test);
3009
3010        let model = cx.read(|cx| {
3011            LanguageModelRegistry::read_global(cx)
3012                .active_model()
3013                .unwrap()
3014        });
3015        cx.update(assistant_panel::init);
3016        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3017
3018        // Create a new context
3019        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3020        let context = cx.new_model(|cx| {
3021            Context::local(
3022                registry.clone(),
3023                Some(project),
3024                None,
3025                prompt_builder.clone(),
3026                cx,
3027            )
3028        });
3029        let buffer = context.read_with(cx, |context, _| context.buffer.clone());
3030
3031        // Simulate user input
3032        let user_message = indoc! {r#"
3033            Please add unnecessary complexity to this code:
3034
3035            ```hello.rs
3036            fn main() {
3037                println!("Hello, World!");
3038            }
3039            ```
3040        "#};
3041        buffer.update(cx, |buffer, cx| {
3042            buffer.edit([(0..0, user_message)], None, cx);
3043        });
3044
3045        // Simulate LLM response with edit steps
3046        let llm_response = indoc! {r#"
3047            Sure, I can help you with that. Here's a step-by-step process:
3048
3049            <step>
3050            First, let's extract the greeting into a separate function:
3051
3052            ```rust
3053            fn greet() {
3054                println!("Hello, World!");
3055            }
3056
3057            fn main() {
3058                greet();
3059            }
3060            ```
3061            </step>
3062
3063            <step>
3064            Now, let's make the greeting customizable:
3065
3066            ```rust
3067            fn greet(name: &str) {
3068                println!("Hello, {}!", name);
3069            }
3070
3071            fn main() {
3072                greet("World");
3073            }
3074            ```
3075            </step>
3076
3077            These changes make the code more modular and flexible.
3078        "#};
3079
3080        // Simulate the assist method to trigger the LLM response
3081        context.update(cx, |context, cx| context.assist(cx));
3082        cx.run_until_parked();
3083
3084        // Retrieve the assistant response message's start from the context
3085        let response_start_row = context.read_with(cx, |context, cx| {
3086            let buffer = context.buffer.read(cx);
3087            context.message_anchors[1].start.to_point(buffer).row
3088        });
3089
3090        // Simulate the LLM completion
3091        model
3092            .as_fake()
3093            .stream_last_completion_response(llm_response.to_string());
3094        model.as_fake().end_last_completion_stream();
3095
3096        // Wait for the completion to be processed
3097        cx.run_until_parked();
3098
3099        // Verify that the edit steps were parsed correctly
3100        context.read_with(cx, |context, cx| {
3101            assert_eq!(
3102                workflow_steps(context, cx),
3103                vec![
3104                    (
3105                        Point::new(response_start_row + 2, 0)
3106                            ..Point::new(response_start_row + 13, 3),
3107                        WorkflowStepTestStatus::Pending
3108                    ),
3109                    (
3110                        Point::new(response_start_row + 15, 0)
3111                            ..Point::new(response_start_row + 26, 3),
3112                        WorkflowStepTestStatus::Pending
3113                    ),
3114                ]
3115            );
3116        });
3117
3118        model
3119            .as_fake()
3120            .respond_to_last_tool_use(Ok(serde_json::to_value(tool::WorkflowStepResolution {
3121                step_title: "Title".into(),
3122                suggestions: vec![tool::WorkflowSuggestion {
3123                    path: "/root/hello.rs".into(),
3124                    // Simulate a symbol name that's slightly different than our outline query
3125                    kind: tool::WorkflowSuggestionKind::Update {
3126                        symbol: "fn main()".into(),
3127                        description: "Extract a greeting function".into(),
3128                    },
3129                }],
3130            })
3131            .unwrap()));
3132
3133        // Wait for tool use to be processed.
3134        cx.run_until_parked();
3135
3136        // Verify that the first edit step is not pending anymore.
3137        context.read_with(cx, |context, cx| {
3138            assert_eq!(
3139                workflow_steps(context, cx),
3140                vec![
3141                    (
3142                        Point::new(response_start_row + 2, 0)
3143                            ..Point::new(response_start_row + 13, 3),
3144                        WorkflowStepTestStatus::Resolved
3145                    ),
3146                    (
3147                        Point::new(response_start_row + 15, 0)
3148                            ..Point::new(response_start_row + 26, 3),
3149                        WorkflowStepTestStatus::Pending
3150                    ),
3151                ]
3152            );
3153        });
3154
3155        #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3156        enum WorkflowStepTestStatus {
3157            Pending,
3158            Resolved,
3159            Error,
3160        }
3161
3162        fn workflow_steps(
3163            context: &Context,
3164            cx: &AppContext,
3165        ) -> Vec<(Range<Point>, WorkflowStepTestStatus)> {
3166            context
3167                .workflow_steps
3168                .iter()
3169                .map(|step| {
3170                    let buffer = context.buffer.read(cx);
3171                    let status = match &step.status {
3172                        WorkflowStepStatus::Pending(_) => WorkflowStepTestStatus::Pending,
3173                        WorkflowStepStatus::Resolved { .. } => WorkflowStepTestStatus::Resolved,
3174                        WorkflowStepStatus::Error(_) => WorkflowStepTestStatus::Error,
3175                    };
3176                    (step.tagged_range.to_point(buffer), status)
3177                })
3178                .collect()
3179        }
3180    }
3181
3182    #[gpui::test]
3183    async fn test_serialization(cx: &mut TestAppContext) {
3184        let settings_store = cx.update(SettingsStore::test);
3185        cx.set_global(settings_store);
3186        cx.update(LanguageModelRegistry::test);
3187        cx.update(assistant_panel::init);
3188        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3189        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3190        let context = cx.new_model(|cx| {
3191            Context::local(registry.clone(), None, None, prompt_builder.clone(), cx)
3192        });
3193        let buffer = context.read_with(cx, |context, _| context.buffer.clone());
3194        let message_0 = context.read_with(cx, |context, _| context.message_anchors[0].id);
3195        let message_1 = context.update(cx, |context, cx| {
3196            context
3197                .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx)
3198                .unwrap()
3199        });
3200        let message_2 = context.update(cx, |context, cx| {
3201            context
3202                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3203                .unwrap()
3204        });
3205        buffer.update(cx, |buffer, cx| {
3206            buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx);
3207            buffer.finalize_last_transaction();
3208        });
3209        let _message_3 = context.update(cx, |context, cx| {
3210            context
3211                .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx)
3212                .unwrap()
3213        });
3214        buffer.update(cx, |buffer, cx| buffer.undo(cx));
3215        assert_eq!(buffer.read_with(cx, |buffer, _| buffer.text()), "a\nb\nc\n");
3216        assert_eq!(
3217            cx.read(|cx| messages(&context, cx)),
3218            [
3219                (message_0, Role::User, 0..2),
3220                (message_1.id, Role::Assistant, 2..6),
3221                (message_2.id, Role::System, 6..6),
3222            ]
3223        );
3224
3225        let serialized_context = context.read_with(cx, |context, cx| context.serialize(cx));
3226        let deserialized_context = cx.new_model(|cx| {
3227            Context::deserialize(
3228                serialized_context,
3229                Default::default(),
3230                registry.clone(),
3231                prompt_builder.clone(),
3232                None,
3233                None,
3234                cx,
3235            )
3236        });
3237        let deserialized_buffer =
3238            deserialized_context.read_with(cx, |context, _| context.buffer.clone());
3239        assert_eq!(
3240            deserialized_buffer.read_with(cx, |buffer, _| buffer.text()),
3241            "a\nb\nc\n"
3242        );
3243        assert_eq!(
3244            cx.read(|cx| messages(&deserialized_context, cx)),
3245            [
3246                (message_0, Role::User, 0..2),
3247                (message_1.id, Role::Assistant, 2..6),
3248                (message_2.id, Role::System, 6..6),
3249            ]
3250        );
3251    }
3252
3253    #[gpui::test(iterations = 100)]
3254    async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: StdRng) {
3255        let min_peers = env::var("MIN_PEERS")
3256            .map(|i| i.parse().expect("invalid `MIN_PEERS` variable"))
3257            .unwrap_or(2);
3258        let max_peers = env::var("MAX_PEERS")
3259            .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
3260            .unwrap_or(5);
3261        let operations = env::var("OPERATIONS")
3262            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3263            .unwrap_or(50);
3264
3265        let settings_store = cx.update(SettingsStore::test);
3266        cx.set_global(settings_store);
3267        cx.update(LanguageModelRegistry::test);
3268
3269        cx.update(assistant_panel::init);
3270        let slash_commands = cx.update(SlashCommandRegistry::default_global);
3271        slash_commands.register_command(FakeSlashCommand("cmd-1".into()), false);
3272        slash_commands.register_command(FakeSlashCommand("cmd-2".into()), false);
3273        slash_commands.register_command(FakeSlashCommand("cmd-3".into()), false);
3274
3275        let registry = Arc::new(LanguageRegistry::test(cx.background_executor.clone()));
3276        let network = Arc::new(Mutex::new(Network::new(rng.clone())));
3277        let mut contexts = Vec::new();
3278
3279        let num_peers = rng.gen_range(min_peers..=max_peers);
3280        let context_id = ContextId::new();
3281        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3282        for i in 0..num_peers {
3283            let context = cx.new_model(|cx| {
3284                Context::new(
3285                    context_id.clone(),
3286                    i as ReplicaId,
3287                    language::Capability::ReadWrite,
3288                    registry.clone(),
3289                    prompt_builder.clone(),
3290                    None,
3291                    None,
3292                    cx,
3293                )
3294            });
3295
3296            cx.update(|cx| {
3297                cx.subscribe(&context, {
3298                    let network = network.clone();
3299                    move |_, event, _| {
3300                        if let ContextEvent::Operation(op) = event {
3301                            network
3302                                .lock()
3303                                .broadcast(i as ReplicaId, vec![op.to_proto()]);
3304                        }
3305                    }
3306                })
3307                .detach();
3308            });
3309
3310            contexts.push(context);
3311            network.lock().add_peer(i as ReplicaId);
3312        }
3313
3314        let mut mutation_count = operations;
3315
3316        while mutation_count > 0
3317            || !network.lock().is_idle()
3318            || network.lock().contains_disconnected_peers()
3319        {
3320            let context_index = rng.gen_range(0..contexts.len());
3321            let context = &contexts[context_index];
3322
3323            match rng.gen_range(0..100) {
3324                0..=29 if mutation_count > 0 => {
3325                    log::info!("Context {}: edit buffer", context_index);
3326                    context.update(cx, |context, cx| {
3327                        context
3328                            .buffer
3329                            .update(cx, |buffer, cx| buffer.randomly_edit(&mut rng, 1, cx));
3330                    });
3331                    mutation_count -= 1;
3332                }
3333                30..=44 if mutation_count > 0 => {
3334                    context.update(cx, |context, cx| {
3335                        let range = context.buffer.read(cx).random_byte_range(0, &mut rng);
3336                        log::info!("Context {}: split message at {:?}", context_index, range);
3337                        context.split_message(range, cx);
3338                    });
3339                    mutation_count -= 1;
3340                }
3341                45..=59 if mutation_count > 0 => {
3342                    context.update(cx, |context, cx| {
3343                        if let Some(message) = context.messages(cx).choose(&mut rng) {
3344                            let role = *[Role::User, Role::Assistant, Role::System]
3345                                .choose(&mut rng)
3346                                .unwrap();
3347                            log::info!(
3348                                "Context {}: insert message after {:?} with {:?}",
3349                                context_index,
3350                                message.id,
3351                                role
3352                            );
3353                            context.insert_message_after(message.id, role, MessageStatus::Done, cx);
3354                        }
3355                    });
3356                    mutation_count -= 1;
3357                }
3358                60..=74 if mutation_count > 0 => {
3359                    context.update(cx, |context, cx| {
3360                        let command_text = "/".to_string()
3361                            + slash_commands
3362                                .command_names()
3363                                .choose(&mut rng)
3364                                .unwrap()
3365                                .clone()
3366                                .as_ref();
3367
3368                        let command_range = context.buffer.update(cx, |buffer, cx| {
3369                            let offset = buffer.random_byte_range(0, &mut rng).start;
3370                            buffer.edit(
3371                                [(offset..offset, format!("\n{}\n", command_text))],
3372                                None,
3373                                cx,
3374                            );
3375                            offset + 1..offset + 1 + command_text.len()
3376                        });
3377
3378                        let output_len = rng.gen_range(1..=10);
3379                        let output_text = RandomCharIter::new(&mut rng)
3380                            .filter(|c| *c != '\r')
3381                            .take(output_len)
3382                            .collect::<String>();
3383
3384                        let num_sections = rng.gen_range(0..=3);
3385                        let mut sections = Vec::with_capacity(num_sections);
3386                        for _ in 0..num_sections {
3387                            let section_start = rng.gen_range(0..output_len);
3388                            let section_end = rng.gen_range(section_start..=output_len);
3389                            sections.push(SlashCommandOutputSection {
3390                                range: section_start..section_end,
3391                                icon: ui::IconName::Ai,
3392                                label: "section".into(),
3393                            });
3394                        }
3395
3396                        log::info!(
3397                            "Context {}: insert slash command output at {:?} with {:?}",
3398                            context_index,
3399                            command_range,
3400                            sections
3401                        );
3402
3403                        let command_range =
3404                            context.buffer.read(cx).anchor_after(command_range.start)
3405                                ..context.buffer.read(cx).anchor_after(command_range.end);
3406                        context.insert_command_output(
3407                            command_range,
3408                            Task::ready(Ok(SlashCommandOutput {
3409                                text: output_text,
3410                                sections,
3411                                run_commands_in_text: false,
3412                            })),
3413                            true,
3414                            cx,
3415                        );
3416                    });
3417                    cx.run_until_parked();
3418                    mutation_count -= 1;
3419                }
3420                75..=84 if mutation_count > 0 => {
3421                    context.update(cx, |context, cx| {
3422                        if let Some(message) = context.messages(cx).choose(&mut rng) {
3423                            let new_status = match rng.gen_range(0..3) {
3424                                0 => MessageStatus::Done,
3425                                1 => MessageStatus::Pending,
3426                                _ => MessageStatus::Error(SharedString::from("Random error")),
3427                            };
3428                            log::info!(
3429                                "Context {}: update message {:?} status to {:?}",
3430                                context_index,
3431                                message.id,
3432                                new_status
3433                            );
3434                            context.update_metadata(message.id, cx, |metadata| {
3435                                metadata.status = new_status;
3436                            });
3437                        }
3438                    });
3439                    mutation_count -= 1;
3440                }
3441                _ => {
3442                    let replica_id = context_index as ReplicaId;
3443                    if network.lock().is_disconnected(replica_id) {
3444                        network.lock().reconnect_peer(replica_id, 0);
3445
3446                        let (ops_to_send, ops_to_receive) = cx.read(|cx| {
3447                            let host_context = &contexts[0].read(cx);
3448                            let guest_context = context.read(cx);
3449                            (
3450                                guest_context.serialize_ops(&host_context.version(cx), cx),
3451                                host_context.serialize_ops(&guest_context.version(cx), cx),
3452                            )
3453                        });
3454                        let ops_to_send = ops_to_send.await;
3455                        let ops_to_receive = ops_to_receive
3456                            .await
3457                            .into_iter()
3458                            .map(ContextOperation::from_proto)
3459                            .collect::<Result<Vec<_>>>()
3460                            .unwrap();
3461                        log::info!(
3462                            "Context {}: reconnecting. Sent {} operations, received {} operations",
3463                            context_index,
3464                            ops_to_send.len(),
3465                            ops_to_receive.len()
3466                        );
3467
3468                        network.lock().broadcast(replica_id, ops_to_send);
3469                        context
3470                            .update(cx, |context, cx| context.apply_ops(ops_to_receive, cx))
3471                            .unwrap();
3472                    } else if rng.gen_bool(0.1) && replica_id != 0 {
3473                        log::info!("Context {}: disconnecting", context_index);
3474                        network.lock().disconnect_peer(replica_id);
3475                    } else if network.lock().has_unreceived(replica_id) {
3476                        log::info!("Context {}: applying operations", context_index);
3477                        let ops = network.lock().receive(replica_id);
3478                        let ops = ops
3479                            .into_iter()
3480                            .map(ContextOperation::from_proto)
3481                            .collect::<Result<Vec<_>>>()
3482                            .unwrap();
3483                        context
3484                            .update(cx, |context, cx| context.apply_ops(ops, cx))
3485                            .unwrap();
3486                    }
3487                }
3488            }
3489        }
3490
3491        cx.read(|cx| {
3492            let first_context = contexts[0].read(cx);
3493            for context in &contexts[1..] {
3494                let context = context.read(cx);
3495                assert!(context.pending_ops.is_empty());
3496                assert_eq!(
3497                    context.buffer.read(cx).text(),
3498                    first_context.buffer.read(cx).text(),
3499                    "Context {} text != Context 0 text",
3500                    context.buffer.read(cx).replica_id()
3501                );
3502                assert_eq!(
3503                    context.message_anchors,
3504                    first_context.message_anchors,
3505                    "Context {} messages != Context 0 messages",
3506                    context.buffer.read(cx).replica_id()
3507                );
3508                assert_eq!(
3509                    context.messages_metadata,
3510                    first_context.messages_metadata,
3511                    "Context {} message metadata != Context 0 message metadata",
3512                    context.buffer.read(cx).replica_id()
3513                );
3514                assert_eq!(
3515                    context.slash_command_output_sections,
3516                    first_context.slash_command_output_sections,
3517                    "Context {} slash command output sections != Context 0 slash command output sections",
3518                    context.buffer.read(cx).replica_id()
3519                );
3520            }
3521        });
3522    }
3523
3524    fn messages(context: &Model<Context>, cx: &AppContext) -> Vec<(MessageId, Role, Range<usize>)> {
3525        context
3526            .read(cx)
3527            .messages(cx)
3528            .map(|message| (message.id, message.role, message.offset_range))
3529            .collect()
3530    }
3531
3532    #[derive(Clone)]
3533    struct FakeSlashCommand(String);
3534
3535    impl SlashCommand for FakeSlashCommand {
3536        fn name(&self) -> String {
3537            self.0.clone()
3538        }
3539
3540        fn description(&self) -> String {
3541            format!("Fake slash command: {}", self.0)
3542        }
3543
3544        fn menu_text(&self) -> String {
3545            format!("Run fake command: {}", self.0)
3546        }
3547
3548        fn complete_argument(
3549            self: Arc<Self>,
3550            _query: String,
3551            _cancel: Arc<AtomicBool>,
3552            _workspace: Option<WeakView<Workspace>>,
3553            _cx: &mut AppContext,
3554        ) -> Task<Result<Vec<ArgumentCompletion>>> {
3555            Task::ready(Ok(vec![]))
3556        }
3557
3558        fn requires_argument(&self) -> bool {
3559            false
3560        }
3561
3562        fn run(
3563            self: Arc<Self>,
3564            _argument: Option<&str>,
3565            _workspace: WeakView<Workspace>,
3566            _delegate: Option<Arc<dyn LspAdapterDelegate>>,
3567            _cx: &mut WindowContext,
3568        ) -> Task<Result<SlashCommandOutput>> {
3569            Task::ready(Ok(SlashCommandOutput {
3570                text: format!("Executed fake command: {}", self.0),
3571                sections: vec![],
3572                run_commands_in_text: false,
3573            }))
3574        }
3575    }
3576}
3577
3578mod tool {
3579    use gpui::AsyncAppContext;
3580
3581    use super::*;
3582
3583    #[derive(Debug, Serialize, Deserialize, JsonSchema)]
3584    pub struct WorkflowStepResolution {
3585        /// An extremely short title for the edit step represented by these operations.
3586        pub step_title: String,
3587        /// A sequence of operations to apply to the codebase.
3588        /// When multiple operations are required for a step, be sure to include multiple operations in this list.
3589        pub suggestions: Vec<WorkflowSuggestion>,
3590    }
3591
3592    impl LanguageModelTool for WorkflowStepResolution {
3593        fn name() -> String {
3594            "edit".into()
3595        }
3596
3597        fn description() -> String {
3598            "suggest edits to one or more locations in the codebase".into()
3599        }
3600    }
3601
3602    /// A description of an operation to apply to one location in the codebase.
3603    ///
3604    /// This object represents a single edit operation that can be performed on a specific file
3605    /// in the codebase. It encapsulates both the location (file path) and the nature of the
3606    /// edit to be made.
3607    ///
3608    /// # Fields
3609    ///
3610    /// * `path`: A string representing the file path where the edit operation should be applied.
3611    ///           This path is relative to the root of the project or repository.
3612    ///
3613    /// * `kind`: An enum representing the specific type of edit operation to be performed.
3614    ///
3615    /// # Usage
3616    ///
3617    /// `EditOperation` is used within a code editor to represent and apply
3618    /// programmatic changes to source code. It provides a structured way to describe
3619    /// edits for features like refactoring tools or AI-assisted coding suggestions.
3620    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
3621    pub struct WorkflowSuggestion {
3622        /// The path to the file containing the relevant operation
3623        pub path: String,
3624        #[serde(flatten)]
3625        pub kind: WorkflowSuggestionKind,
3626    }
3627
3628    impl WorkflowSuggestion {
3629        pub(super) async fn resolve(
3630            &self,
3631            project: Model<Project>,
3632            mut cx: AsyncAppContext,
3633        ) -> Result<(Model<Buffer>, super::WorkflowSuggestion)> {
3634            let path = self.path.clone();
3635            let kind = self.kind.clone();
3636            let buffer = project
3637                .update(&mut cx, |project, cx| {
3638                    let project_path = project
3639                        .find_project_path(Path::new(&path), cx)
3640                        .with_context(|| format!("worktree not found for {:?}", path))?;
3641                    anyhow::Ok(project.open_buffer(project_path, cx))
3642                })??
3643                .await?;
3644
3645            let mut parse_status = buffer.read_with(&cx, |buffer, _cx| buffer.parse_status())?;
3646            while *parse_status.borrow() != ParseStatus::Idle {
3647                parse_status.changed().await?;
3648            }
3649
3650            let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
3651            let outline = snapshot.outline(None).context("no outline for buffer")?;
3652
3653            let suggestion;
3654            match kind {
3655                WorkflowSuggestionKind::Update {
3656                    symbol,
3657                    description,
3658                } => {
3659                    let symbol = outline
3660                        .find_most_similar(&symbol)
3661                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3662                        .to_point(&snapshot);
3663                    let start = symbol
3664                        .annotation_range
3665                        .map_or(symbol.range.start, |range| range.start);
3666                    let start = Point::new(start.row, 0);
3667                    let end = Point::new(
3668                        symbol.range.end.row,
3669                        snapshot.line_len(symbol.range.end.row),
3670                    );
3671                    let range = snapshot.anchor_before(start)..snapshot.anchor_after(end);
3672                    suggestion = super::WorkflowSuggestion::Update { range, description };
3673                }
3674                WorkflowSuggestionKind::Create { description } => {
3675                    suggestion = super::WorkflowSuggestion::CreateFile { description };
3676                }
3677                WorkflowSuggestionKind::InsertSiblingBefore {
3678                    symbol,
3679                    description,
3680                } => {
3681                    let symbol = outline
3682                        .find_most_similar(&symbol)
3683                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3684                        .to_point(&snapshot);
3685                    let position = snapshot.anchor_before(
3686                        symbol
3687                            .annotation_range
3688                            .map_or(symbol.range.start, |annotation_range| {
3689                                annotation_range.start
3690                            }),
3691                    );
3692                    suggestion = super::WorkflowSuggestion::InsertSiblingBefore {
3693                        position,
3694                        description,
3695                    };
3696                }
3697                WorkflowSuggestionKind::InsertSiblingAfter {
3698                    symbol,
3699                    description,
3700                } => {
3701                    let symbol = outline
3702                        .find_most_similar(&symbol)
3703                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3704                        .to_point(&snapshot);
3705                    let position = snapshot.anchor_after(symbol.range.end);
3706                    suggestion = super::WorkflowSuggestion::InsertSiblingAfter {
3707                        position,
3708                        description,
3709                    };
3710                }
3711                WorkflowSuggestionKind::PrependChild {
3712                    symbol,
3713                    description,
3714                } => {
3715                    if let Some(symbol) = symbol {
3716                        let symbol = outline
3717                            .find_most_similar(&symbol)
3718                            .with_context(|| format!("symbol not found: {:?}", symbol))?
3719                            .to_point(&snapshot);
3720
3721                        let position = snapshot.anchor_after(
3722                            symbol
3723                                .body_range
3724                                .map_or(symbol.range.start, |body_range| body_range.start),
3725                        );
3726                        suggestion = super::WorkflowSuggestion::PrependChild {
3727                            position,
3728                            description,
3729                        };
3730                    } else {
3731                        suggestion = super::WorkflowSuggestion::PrependChild {
3732                            position: language::Anchor::MIN,
3733                            description,
3734                        };
3735                    }
3736                }
3737                WorkflowSuggestionKind::AppendChild {
3738                    symbol,
3739                    description,
3740                } => {
3741                    if let Some(symbol) = symbol {
3742                        let symbol = outline
3743                            .find_most_similar(&symbol)
3744                            .with_context(|| format!("symbol not found: {:?}", symbol))?
3745                            .to_point(&snapshot);
3746
3747                        let position = snapshot.anchor_before(
3748                            symbol
3749                                .body_range
3750                                .map_or(symbol.range.end, |body_range| body_range.end),
3751                        );
3752                        suggestion = super::WorkflowSuggestion::AppendChild {
3753                            position,
3754                            description,
3755                        };
3756                    } else {
3757                        suggestion = super::WorkflowSuggestion::PrependChild {
3758                            position: language::Anchor::MAX,
3759                            description,
3760                        };
3761                    }
3762                }
3763                WorkflowSuggestionKind::Delete { symbol } => {
3764                    let symbol = outline
3765                        .find_most_similar(&symbol)
3766                        .with_context(|| format!("symbol not found: {:?}", symbol))?
3767                        .to_point(&snapshot);
3768                    let start = symbol
3769                        .annotation_range
3770                        .map_or(symbol.range.start, |range| range.start);
3771                    let start = Point::new(start.row, 0);
3772                    let end = Point::new(
3773                        symbol.range.end.row,
3774                        snapshot.line_len(symbol.range.end.row),
3775                    );
3776                    let range = snapshot.anchor_before(start)..snapshot.anchor_after(end);
3777                    suggestion = super::WorkflowSuggestion::Delete { range };
3778                }
3779            }
3780
3781            Ok((buffer, suggestion))
3782        }
3783    }
3784
3785    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
3786    #[serde(tag = "kind")]
3787    pub enum WorkflowSuggestionKind {
3788        /// Rewrites the specified symbol entirely based on the given description.
3789        /// This operation completely replaces the existing symbol with new content.
3790        Update {
3791            /// A fully-qualified reference to the symbol, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
3792            /// The path should uniquely identify the symbol within the containing file.
3793            symbol: String,
3794            /// A brief description of the transformation to apply to the symbol.
3795            description: String,
3796        },
3797        /// Creates a new file with the given path based on the provided description.
3798        /// This operation adds a new file to the codebase.
3799        Create {
3800            /// A brief description of the file to be created.
3801            description: String,
3802        },
3803        /// Inserts a new symbol based on the given description before the specified symbol.
3804        /// This operation adds new content immediately preceding an existing symbol.
3805        InsertSiblingBefore {
3806            /// A fully-qualified reference to the symbol, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
3807            /// The new content will be inserted immediately before this symbol.
3808            symbol: String,
3809            /// A brief description of the new symbol to be inserted.
3810            description: String,
3811        },
3812        /// Inserts a new symbol based on the given description after the specified symbol.
3813        /// This operation adds new content immediately following an existing symbol.
3814        InsertSiblingAfter {
3815            /// A fully-qualified reference to the symbol, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
3816            /// The new content will be inserted immediately after this symbol.
3817            symbol: String,
3818            /// A brief description of the new symbol to be inserted.
3819            description: String,
3820        },
3821        /// Inserts a new symbol as a child of the specified symbol at the start.
3822        /// This operation adds new content as the first child of an existing symbol (or file if no symbol is provided).
3823        PrependChild {
3824            /// 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`.
3825            /// If provided, the new content will be inserted as the first child of this symbol.
3826            /// If not provided, the new content will be inserted at the top of the file.
3827            symbol: Option<String>,
3828            /// A brief description of the new symbol to be inserted.
3829            description: String,
3830        },
3831        /// Inserts a new symbol as a child of the specified symbol at the end.
3832        /// This operation adds new content as the last child of an existing symbol (or file if no symbol is provided).
3833        AppendChild {
3834            /// 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`.
3835            /// If provided, the new content will be inserted as the last child of this symbol.
3836            /// If not provided, the new content will be applied at the bottom of the file.
3837            symbol: Option<String>,
3838            /// A brief description of the new symbol to be inserted.
3839            description: String,
3840        },
3841        /// Deletes the specified symbol from the containing file.
3842        Delete {
3843            /// An fully-qualified reference to the symbol to be deleted, e.g. `mod foo impl Bar pub fn baz` instead of just `fn baz`.
3844            symbol: String,
3845        },
3846    }
3847
3848    impl WorkflowSuggestionKind {
3849        pub fn symbol(&self) -> Option<&str> {
3850            match self {
3851                Self::Update { symbol, .. } => Some(symbol),
3852                Self::InsertSiblingBefore { symbol, .. } => Some(symbol),
3853                Self::InsertSiblingAfter { symbol, .. } => Some(symbol),
3854                Self::PrependChild { symbol, .. } => symbol.as_deref(),
3855                Self::AppendChild { symbol, .. } => symbol.as_deref(),
3856                Self::Delete { symbol } => Some(symbol),
3857                Self::Create { .. } => None,
3858            }
3859        }
3860
3861        pub fn description(&self) -> Option<&str> {
3862            match self {
3863                Self::Update { description, .. } => Some(description),
3864                Self::Create { description } => Some(description),
3865                Self::InsertSiblingBefore { description, .. } => Some(description),
3866                Self::InsertSiblingAfter { description, .. } => Some(description),
3867                Self::PrependChild { description, .. } => Some(description),
3868                Self::AppendChild { description, .. } => Some(description),
3869                Self::Delete { .. } => None,
3870            }
3871        }
3872
3873        pub fn initial_insertion(&self) -> Option<InitialInsertion> {
3874            match self {
3875                WorkflowSuggestionKind::InsertSiblingBefore { .. } => {
3876                    Some(InitialInsertion::NewlineAfter)
3877                }
3878                WorkflowSuggestionKind::InsertSiblingAfter { .. } => {
3879                    Some(InitialInsertion::NewlineBefore)
3880                }
3881                WorkflowSuggestionKind::PrependChild { .. } => Some(InitialInsertion::NewlineAfter),
3882                WorkflowSuggestionKind::AppendChild { .. } => Some(InitialInsertion::NewlineBefore),
3883                _ => None,
3884            }
3885        }
3886    }
3887}