context.rs

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