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