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