assistant_panel.rs

   1use crate::{
   2    assistant_settings::{AssistantDockPosition, AssistantSettings, OpenAIModel},
   3    codegen::{self, Codegen, CodegenKind},
   4    prompts::generate_content_prompt,
   5    Assist, CycleMessageRole, InlineAssist, MessageId, MessageMetadata, MessageStatus,
   6    NewConversation, QuoteSelection, ResetKey, Role, SavedConversation, SavedConversationMetadata,
   7    SavedMessage, Split, ToggleFocus, ToggleIncludeConversation, ToggleRetrieveContext,
   8};
   9
  10use ai::{
  11    auth::ProviderCredential,
  12    completion::{CompletionProvider, CompletionRequest},
  13    providers::open_ai::{OpenAICompletionProvider, OpenAIRequest, RequestMessage},
  14};
  15
  16use ai::prompts::repository_context::PromptCodeSnippet;
  17use anyhow::{anyhow, Result};
  18use chrono::{DateTime, Local};
  19use client::telemetry::AssistantKind;
  20use collections::{hash_map, HashMap, HashSet, VecDeque};
  21use editor::{
  22    display_map::{
  23        BlockContext, BlockDisposition, BlockId, BlockProperties, BlockStyle, ToDisplayPoint,
  24    },
  25    scroll::autoscroll::{Autoscroll, AutoscrollStrategy},
  26    Anchor, Editor, EditorElement, EditorEvent, EditorStyle, MoveDown, MoveUp, MultiBufferSnapshot,
  27    ToOffset, ToPoint,
  28};
  29use fs::Fs;
  30use futures::StreamExt;
  31use gpui::{
  32    canvas, div, point, relative, rems, uniform_list, Action, AnyElement, AppContext,
  33    AsyncWindowContext, AvailableSpace, ClipboardItem, Context, EventEmitter, FocusHandle,
  34    FocusableView, FontStyle, FontWeight, HighlightStyle, InteractiveElement, IntoElement, Model,
  35    ModelContext, ParentElement, Pixels, PromptLevel, Render, SharedString,
  36    StatefulInteractiveElement, Styled, Subscription, Task, TextStyle, UniformListScrollHandle,
  37    View, ViewContext, VisualContext, WeakModel, WeakView, WhiteSpace, WindowContext,
  38};
  39use language::{language_settings::SoftWrap, Buffer, LanguageRegistry, ToOffset as _};
  40use project::Project;
  41use search::{buffer_search::DivRegistrar, BufferSearchBar};
  42use semantic_index::{SemanticIndex, SemanticIndexStatus};
  43use settings::{Settings, SettingsStore};
  44use std::{
  45    cell::Cell,
  46    cmp,
  47    fmt::Write,
  48    iter,
  49    ops::Range,
  50    path::{Path, PathBuf},
  51    rc::Rc,
  52    sync::Arc,
  53    time::{Duration, Instant},
  54};
  55use theme::ThemeSettings;
  56use ui::{
  57    prelude::*,
  58    utils::{DateTimeType, FormatDistance},
  59    ButtonLike, Tab, TabBar, Tooltip,
  60};
  61use util::{paths::CONVERSATIONS_DIR, post_inc, ResultExt, TryFutureExt};
  62use uuid::Uuid;
  63use workspace::{
  64    dock::{DockPosition, Panel, PanelEvent},
  65    searchable::Direction,
  66    Save, Toast, ToggleZoom, Toolbar, Workspace,
  67};
  68
  69pub fn init(cx: &mut AppContext) {
  70    AssistantSettings::register(cx);
  71    cx.observe_new_views(
  72        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  73            workspace
  74                .register_action(|workspace, _: &ToggleFocus, cx| {
  75                    workspace.toggle_panel_focus::<AssistantPanel>(cx);
  76                })
  77                .register_action(AssistantPanel::inline_assist)
  78                .register_action(AssistantPanel::cancel_last_inline_assist)
  79                .register_action(ConversationEditor::quote_selection);
  80        },
  81    )
  82    .detach();
  83}
  84
  85pub struct AssistantPanel {
  86    workspace: WeakView<Workspace>,
  87    width: Option<Pixels>,
  88    height: Option<Pixels>,
  89    active_editor_index: Option<usize>,
  90    prev_active_editor_index: Option<usize>,
  91    editors: Vec<View<ConversationEditor>>,
  92    saved_conversations: Vec<SavedConversationMetadata>,
  93    saved_conversations_scroll_handle: UniformListScrollHandle,
  94    zoomed: bool,
  95    focus_handle: FocusHandle,
  96    toolbar: View<Toolbar>,
  97    completion_provider: Arc<dyn CompletionProvider>,
  98    api_key_editor: Option<View<Editor>>,
  99    languages: Arc<LanguageRegistry>,
 100    fs: Arc<dyn Fs>,
 101    subscriptions: Vec<Subscription>,
 102    next_inline_assist_id: usize,
 103    pending_inline_assists: HashMap<usize, PendingInlineAssist>,
 104    pending_inline_assist_ids_by_editor: HashMap<WeakView<Editor>, Vec<usize>>,
 105    include_conversation_in_next_inline_assist: bool,
 106    inline_prompt_history: VecDeque<String>,
 107    _watch_saved_conversations: Task<Result<()>>,
 108    semantic_index: Option<Model<SemanticIndex>>,
 109    retrieve_context_in_next_inline_assist: bool,
 110}
 111
 112impl AssistantPanel {
 113    const INLINE_PROMPT_HISTORY_MAX_LEN: usize = 20;
 114
 115    pub fn load(
 116        workspace: WeakView<Workspace>,
 117        cx: AsyncWindowContext,
 118    ) -> Task<Result<View<Self>>> {
 119        cx.spawn(|mut cx| async move {
 120            let fs = workspace.update(&mut cx, |workspace, _| workspace.app_state().fs.clone())?;
 121            let saved_conversations = SavedConversationMetadata::list(fs.clone())
 122                .await
 123                .log_err()
 124                .unwrap_or_default();
 125
 126            // TODO: deserialize state.
 127            let workspace_handle = workspace.clone();
 128            workspace.update(&mut cx, |workspace, cx| {
 129                cx.new_view::<Self>(|cx| {
 130                    const CONVERSATION_WATCH_DURATION: Duration = Duration::from_millis(100);
 131                    let _watch_saved_conversations = cx.spawn(move |this, mut cx| async move {
 132                        let mut events = fs
 133                            .watch(&CONVERSATIONS_DIR, CONVERSATION_WATCH_DURATION)
 134                            .await;
 135                        while events.next().await.is_some() {
 136                            let saved_conversations = SavedConversationMetadata::list(fs.clone())
 137                                .await
 138                                .log_err()
 139                                .unwrap_or_default();
 140                            this.update(&mut cx, |this, cx| {
 141                                this.saved_conversations = saved_conversations;
 142                                cx.notify();
 143                            })
 144                            .ok();
 145                        }
 146
 147                        anyhow::Ok(())
 148                    });
 149
 150                    let toolbar = cx.new_view(|cx| {
 151                        let mut toolbar = Toolbar::new();
 152                        toolbar.set_can_navigate(false, cx);
 153                        toolbar.add_item(cx.new_view(|cx| BufferSearchBar::new(cx)), cx);
 154                        toolbar
 155                    });
 156
 157                    let semantic_index = SemanticIndex::global(cx);
 158                    // Defaulting currently to GPT4, allow for this to be set via config.
 159                    let completion_provider = Arc::new(OpenAICompletionProvider::new(
 160                        "gpt-4",
 161                        cx.background_executor().clone(),
 162                    ));
 163
 164                    let focus_handle = cx.focus_handle();
 165                    cx.on_focus_in(&focus_handle, Self::focus_in).detach();
 166                    cx.on_focus_out(&focus_handle, Self::focus_out).detach();
 167
 168                    let mut this = Self {
 169                        workspace: workspace_handle,
 170                        active_editor_index: Default::default(),
 171                        prev_active_editor_index: Default::default(),
 172                        editors: Default::default(),
 173                        saved_conversations,
 174                        saved_conversations_scroll_handle: Default::default(),
 175                        zoomed: false,
 176                        focus_handle,
 177                        toolbar,
 178                        completion_provider,
 179                        api_key_editor: None,
 180                        languages: workspace.app_state().languages.clone(),
 181                        fs: workspace.app_state().fs.clone(),
 182                        width: None,
 183                        height: None,
 184                        subscriptions: Default::default(),
 185                        next_inline_assist_id: 0,
 186                        pending_inline_assists: Default::default(),
 187                        pending_inline_assist_ids_by_editor: Default::default(),
 188                        include_conversation_in_next_inline_assist: false,
 189                        inline_prompt_history: Default::default(),
 190                        _watch_saved_conversations,
 191                        semantic_index,
 192                        retrieve_context_in_next_inline_assist: false,
 193                    };
 194
 195                    let mut old_dock_position = this.position(cx);
 196                    this.subscriptions =
 197                        vec![cx.observe_global::<SettingsStore>(move |this, cx| {
 198                            let new_dock_position = this.position(cx);
 199                            if new_dock_position != old_dock_position {
 200                                old_dock_position = new_dock_position;
 201                                cx.emit(PanelEvent::ChangePosition);
 202                            }
 203                            cx.notify();
 204                        })];
 205
 206                    this
 207                })
 208            })
 209        })
 210    }
 211
 212    fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
 213        self.toolbar
 214            .update(cx, |toolbar, cx| toolbar.focus_changed(true, cx));
 215        cx.notify();
 216        if self.focus_handle.is_focused(cx) {
 217            if let Some(editor) = self.active_editor() {
 218                cx.focus_view(editor);
 219            } else if let Some(api_key_editor) = self.api_key_editor.as_ref() {
 220                cx.focus_view(api_key_editor);
 221            }
 222        }
 223    }
 224
 225    fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
 226        self.toolbar
 227            .update(cx, |toolbar, cx| toolbar.focus_changed(false, cx));
 228        cx.notify();
 229    }
 230
 231    pub fn inline_assist(
 232        workspace: &mut Workspace,
 233        _: &InlineAssist,
 234        cx: &mut ViewContext<Workspace>,
 235    ) {
 236        let this = if let Some(this) = workspace.panel::<AssistantPanel>(cx) {
 237            if this.update(cx, |assistant, cx| {
 238                if !assistant.has_credentials() {
 239                    assistant.load_credentials(cx);
 240                };
 241
 242                assistant.has_credentials()
 243            }) {
 244                this
 245            } else {
 246                workspace.focus_panel::<AssistantPanel>(cx);
 247                return;
 248            }
 249        } else {
 250            return;
 251        };
 252
 253        let active_editor = if let Some(active_editor) = workspace
 254            .active_item(cx)
 255            .and_then(|item| item.act_as::<Editor>(cx))
 256        {
 257            active_editor
 258        } else {
 259            return;
 260        };
 261
 262        let project = workspace.project();
 263
 264        this.update(cx, |assistant, cx| {
 265            assistant.new_inline_assist(&active_editor, cx, project)
 266        });
 267    }
 268
 269    fn new_inline_assist(
 270        &mut self,
 271        editor: &View<Editor>,
 272        cx: &mut ViewContext<Self>,
 273        project: &Model<Project>,
 274    ) {
 275        let selection = editor.read(cx).selections.newest_anchor().clone();
 276        if selection.start.excerpt_id != selection.end.excerpt_id {
 277            return;
 278        }
 279        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
 280
 281        // Extend the selection to the start and the end of the line.
 282        let mut point_selection = selection.map(|selection| selection.to_point(&snapshot));
 283        if point_selection.end > point_selection.start {
 284            point_selection.start.column = 0;
 285            // If the selection ends at the start of the line, we don't want to include it.
 286            if point_selection.end.column == 0 {
 287                point_selection.end.row -= 1;
 288            }
 289            point_selection.end.column = snapshot.line_len(point_selection.end.row);
 290        }
 291
 292        let codegen_kind = if point_selection.start == point_selection.end {
 293            CodegenKind::Generate {
 294                position: snapshot.anchor_after(point_selection.start),
 295            }
 296        } else {
 297            CodegenKind::Transform {
 298                range: snapshot.anchor_before(point_selection.start)
 299                    ..snapshot.anchor_after(point_selection.end),
 300            }
 301        };
 302
 303        let inline_assist_id = post_inc(&mut self.next_inline_assist_id);
 304        let provider = self.completion_provider.clone();
 305
 306        // Retrieve Credentials Authenticates the Provider
 307        provider.retrieve_credentials(cx);
 308
 309        let codegen = cx.new_model(|cx| {
 310            Codegen::new(editor.read(cx).buffer().clone(), codegen_kind, provider, cx)
 311        });
 312
 313        if let Some(semantic_index) = self.semantic_index.clone() {
 314            let project = project.clone();
 315            cx.spawn(|_, mut cx| async move {
 316                let previously_indexed = semantic_index
 317                    .update(&mut cx, |index, cx| {
 318                        index.project_previously_indexed(&project, cx)
 319                    })?
 320                    .await
 321                    .unwrap_or(false);
 322                if previously_indexed {
 323                    let _ = semantic_index
 324                        .update(&mut cx, |index, cx| {
 325                            index.index_project(project.clone(), cx)
 326                        })?
 327                        .await;
 328                }
 329                anyhow::Ok(())
 330            })
 331            .detach_and_log_err(cx);
 332        }
 333
 334        let measurements = Rc::new(Cell::new(BlockMeasurements::default()));
 335        let inline_assistant = cx.new_view(|cx| {
 336            InlineAssistant::new(
 337                inline_assist_id,
 338                measurements.clone(),
 339                self.include_conversation_in_next_inline_assist,
 340                self.inline_prompt_history.clone(),
 341                codegen.clone(),
 342                self.workspace.clone(),
 343                cx,
 344                self.retrieve_context_in_next_inline_assist,
 345                self.semantic_index.clone(),
 346                project.clone(),
 347            )
 348        });
 349        let block_id = editor.update(cx, |editor, cx| {
 350            editor.change_selections(None, cx, |selections| {
 351                selections.select_anchor_ranges([selection.head()..selection.head()])
 352            });
 353            editor.insert_blocks(
 354                [BlockProperties {
 355                    style: BlockStyle::Flex,
 356                    position: snapshot.anchor_before(point_selection.head()),
 357                    height: 2,
 358                    render: Arc::new({
 359                        let inline_assistant = inline_assistant.clone();
 360                        move |cx: &mut BlockContext| {
 361                            measurements.set(BlockMeasurements {
 362                                anchor_x: cx.anchor_x,
 363                                gutter_width: cx.gutter_width,
 364                            });
 365                            inline_assistant.clone().into_any_element()
 366                        }
 367                    }),
 368                    disposition: if selection.reversed {
 369                        BlockDisposition::Above
 370                    } else {
 371                        BlockDisposition::Below
 372                    },
 373                }],
 374                Some(Autoscroll::Strategy(AutoscrollStrategy::Newest)),
 375                cx,
 376            )[0]
 377        });
 378
 379        self.pending_inline_assists.insert(
 380            inline_assist_id,
 381            PendingInlineAssist {
 382                editor: editor.downgrade(),
 383                inline_assistant: Some((block_id, inline_assistant.clone())),
 384                codegen: codegen.clone(),
 385                project: project.downgrade(),
 386                _subscriptions: vec![
 387                    cx.subscribe(&inline_assistant, Self::handle_inline_assistant_event),
 388                    cx.subscribe(editor, {
 389                        let inline_assistant = inline_assistant.downgrade();
 390                        move |_, editor, event, cx| {
 391                            if let Some(inline_assistant) = inline_assistant.upgrade() {
 392                                if let EditorEvent::SelectionsChanged { local } = event {
 393                                    if *local
 394                                        && inline_assistant.focus_handle(cx).contains_focused(cx)
 395                                    {
 396                                        cx.focus_view(&editor);
 397                                    }
 398                                }
 399                            }
 400                        }
 401                    }),
 402                    cx.observe(&codegen, {
 403                        let editor = editor.downgrade();
 404                        move |this, _, cx| {
 405                            if let Some(editor) = editor.upgrade() {
 406                                this.update_highlights_for_editor(&editor, cx);
 407                            }
 408                        }
 409                    }),
 410                    cx.subscribe(&codegen, move |this, codegen, event, cx| match event {
 411                        codegen::Event::Undone => {
 412                            this.finish_inline_assist(inline_assist_id, false, cx)
 413                        }
 414                        codegen::Event::Finished => {
 415                            let pending_assist = if let Some(pending_assist) =
 416                                this.pending_inline_assists.get(&inline_assist_id)
 417                            {
 418                                pending_assist
 419                            } else {
 420                                return;
 421                            };
 422
 423                            let error = codegen
 424                                .read(cx)
 425                                .error()
 426                                .map(|error| format!("Inline assistant error: {}", error));
 427                            if let Some(error) = error {
 428                                if pending_assist.inline_assistant.is_none() {
 429                                    if let Some(workspace) = this.workspace.upgrade() {
 430                                        workspace.update(cx, |workspace, cx| {
 431                                            workspace.show_toast(
 432                                                Toast::new(inline_assist_id, error),
 433                                                cx,
 434                                            );
 435                                        })
 436                                    }
 437
 438                                    this.finish_inline_assist(inline_assist_id, false, cx);
 439                                }
 440                            } else {
 441                                this.finish_inline_assist(inline_assist_id, false, cx);
 442                            }
 443                        }
 444                    }),
 445                ],
 446            },
 447        );
 448        self.pending_inline_assist_ids_by_editor
 449            .entry(editor.downgrade())
 450            .or_default()
 451            .push(inline_assist_id);
 452        self.update_highlights_for_editor(&editor, cx);
 453    }
 454
 455    fn handle_inline_assistant_event(
 456        &mut self,
 457        inline_assistant: View<InlineAssistant>,
 458        event: &InlineAssistantEvent,
 459        cx: &mut ViewContext<Self>,
 460    ) {
 461        let assist_id = inline_assistant.read(cx).id;
 462        match event {
 463            InlineAssistantEvent::Confirmed {
 464                prompt,
 465                include_conversation,
 466                retrieve_context,
 467            } => {
 468                self.confirm_inline_assist(
 469                    assist_id,
 470                    prompt,
 471                    *include_conversation,
 472                    cx,
 473                    *retrieve_context,
 474                );
 475            }
 476            InlineAssistantEvent::Canceled => {
 477                self.finish_inline_assist(assist_id, true, cx);
 478            }
 479            InlineAssistantEvent::Dismissed => {
 480                self.hide_inline_assist(assist_id, cx);
 481            }
 482            InlineAssistantEvent::IncludeConversationToggled {
 483                include_conversation,
 484            } => {
 485                self.include_conversation_in_next_inline_assist = *include_conversation;
 486            }
 487            InlineAssistantEvent::RetrieveContextToggled { retrieve_context } => {
 488                self.retrieve_context_in_next_inline_assist = *retrieve_context
 489            }
 490        }
 491    }
 492
 493    fn cancel_last_inline_assist(
 494        workspace: &mut Workspace,
 495        _: &editor::Cancel,
 496        cx: &mut ViewContext<Workspace>,
 497    ) {
 498        if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
 499            if let Some(editor) = workspace
 500                .active_item(cx)
 501                .and_then(|item| item.downcast::<Editor>())
 502            {
 503                let handled = panel.update(cx, |panel, cx| {
 504                    if let Some(assist_id) = panel
 505                        .pending_inline_assist_ids_by_editor
 506                        .get(&editor.downgrade())
 507                        .and_then(|assist_ids| assist_ids.last().copied())
 508                    {
 509                        panel.finish_inline_assist(assist_id, true, cx);
 510                        true
 511                    } else {
 512                        false
 513                    }
 514                });
 515                if handled {
 516                    return;
 517                }
 518            }
 519        }
 520
 521        cx.propagate();
 522    }
 523
 524    fn finish_inline_assist(&mut self, assist_id: usize, undo: bool, cx: &mut ViewContext<Self>) {
 525        self.hide_inline_assist(assist_id, cx);
 526
 527        if let Some(pending_assist) = self.pending_inline_assists.remove(&assist_id) {
 528            if let hash_map::Entry::Occupied(mut entry) = self
 529                .pending_inline_assist_ids_by_editor
 530                .entry(pending_assist.editor.clone())
 531            {
 532                entry.get_mut().retain(|id| *id != assist_id);
 533                if entry.get().is_empty() {
 534                    entry.remove();
 535                }
 536            }
 537
 538            if let Some(editor) = pending_assist.editor.upgrade() {
 539                self.update_highlights_for_editor(&editor, cx);
 540
 541                if undo {
 542                    pending_assist
 543                        .codegen
 544                        .update(cx, |codegen, cx| codegen.undo(cx));
 545                }
 546            }
 547        }
 548    }
 549
 550    fn hide_inline_assist(&mut self, assist_id: usize, cx: &mut ViewContext<Self>) {
 551        if let Some(pending_assist) = self.pending_inline_assists.get_mut(&assist_id) {
 552            if let Some(editor) = pending_assist.editor.upgrade() {
 553                if let Some((block_id, inline_assistant)) = pending_assist.inline_assistant.take() {
 554                    editor.update(cx, |editor, cx| {
 555                        editor.remove_blocks(HashSet::from_iter([block_id]), None, cx);
 556                        if inline_assistant.focus_handle(cx).contains_focused(cx) {
 557                            editor.focus(cx);
 558                        }
 559                    });
 560                }
 561            }
 562        }
 563    }
 564
 565    fn confirm_inline_assist(
 566        &mut self,
 567        inline_assist_id: usize,
 568        user_prompt: &str,
 569        include_conversation: bool,
 570        cx: &mut ViewContext<Self>,
 571        retrieve_context: bool,
 572    ) {
 573        let conversation = if include_conversation {
 574            self.active_editor()
 575                .map(|editor| editor.read(cx).conversation.clone())
 576        } else {
 577            None
 578        };
 579
 580        let pending_assist =
 581            if let Some(pending_assist) = self.pending_inline_assists.get_mut(&inline_assist_id) {
 582                pending_assist
 583            } else {
 584                return;
 585            };
 586
 587        let editor = if let Some(editor) = pending_assist.editor.upgrade() {
 588            editor
 589        } else {
 590            return;
 591        };
 592
 593        let project = pending_assist.project.clone();
 594
 595        let project_name = if let Some(project) = project.upgrade() {
 596            Some(
 597                project
 598                    .read(cx)
 599                    .worktree_root_names(cx)
 600                    .collect::<Vec<&str>>()
 601                    .join("/"),
 602            )
 603        } else {
 604            None
 605        };
 606
 607        self.inline_prompt_history
 608            .retain(|prompt| prompt != user_prompt);
 609        self.inline_prompt_history.push_back(user_prompt.into());
 610        if self.inline_prompt_history.len() > Self::INLINE_PROMPT_HISTORY_MAX_LEN {
 611            self.inline_prompt_history.pop_front();
 612        }
 613
 614        let codegen = pending_assist.codegen.clone();
 615        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
 616        let range = codegen.read(cx).range();
 617        let start = snapshot.point_to_buffer_offset(range.start);
 618        let end = snapshot.point_to_buffer_offset(range.end);
 619        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
 620            let (start_buffer, start_buffer_offset) = start;
 621            let (end_buffer, end_buffer_offset) = end;
 622            if start_buffer.remote_id() == end_buffer.remote_id() {
 623                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
 624            } else {
 625                self.finish_inline_assist(inline_assist_id, false, cx);
 626                return;
 627            }
 628        } else {
 629            self.finish_inline_assist(inline_assist_id, false, cx);
 630            return;
 631        };
 632
 633        let language = buffer.language_at(range.start);
 634        let language_name = if let Some(language) = language.as_ref() {
 635            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
 636                None
 637            } else {
 638                Some(language.name())
 639            }
 640        } else {
 641            None
 642        };
 643
 644        // Higher Temperature increases the randomness of model outputs.
 645        // If Markdown or No Language is Known, increase the randomness for more creative output
 646        // If Code, decrease temperature to get more deterministic outputs
 647        let temperature = if let Some(language) = language_name.clone() {
 648            if language.to_string() != "Markdown".to_string() {
 649                0.5
 650            } else {
 651                1.0
 652            }
 653        } else {
 654            1.0
 655        };
 656
 657        let user_prompt = user_prompt.to_string();
 658
 659        let snippets = if retrieve_context {
 660            let Some(project) = project.upgrade() else {
 661                return;
 662            };
 663
 664            let search_results = if let Some(semantic_index) = self.semantic_index.clone() {
 665                let search_results = semantic_index.update(cx, |this, cx| {
 666                    this.search_project(project, user_prompt.to_string(), 10, vec![], vec![], cx)
 667                });
 668
 669                cx.background_executor()
 670                    .spawn(async move { search_results.await.unwrap_or_default() })
 671            } else {
 672                Task::ready(Vec::new())
 673            };
 674
 675            let snippets = cx.spawn(|_, mut cx| async move {
 676                let mut snippets = Vec::new();
 677                for result in search_results.await {
 678                    snippets.push(PromptCodeSnippet::new(
 679                        result.buffer,
 680                        result.range,
 681                        &mut cx,
 682                    )?);
 683                }
 684                anyhow::Ok(snippets)
 685            });
 686            snippets
 687        } else {
 688            Task::ready(Ok(Vec::new()))
 689        };
 690
 691        let mut model = AssistantSettings::get_global(cx)
 692            .default_open_ai_model
 693            .clone();
 694        let model_name = model.full_name();
 695
 696        let prompt = cx.background_executor().spawn(async move {
 697            let snippets = snippets.await?;
 698
 699            let language_name = language_name.as_deref();
 700            generate_content_prompt(
 701                user_prompt,
 702                language_name,
 703                buffer,
 704                range,
 705                snippets,
 706                model_name,
 707                project_name,
 708            )
 709        });
 710
 711        let mut messages = Vec::new();
 712        if let Some(conversation) = conversation {
 713            let conversation = conversation.read(cx);
 714            let buffer = conversation.buffer.read(cx);
 715            messages.extend(
 716                conversation
 717                    .messages(cx)
 718                    .map(|message| message.to_open_ai_message(buffer)),
 719            );
 720            model = conversation.model.clone();
 721        }
 722
 723        cx.spawn(|_, mut cx| async move {
 724            // I Don't know if we want to return a ? here.
 725            let prompt = prompt.await?;
 726
 727            messages.push(RequestMessage {
 728                role: Role::User,
 729                content: prompt,
 730            });
 731
 732            let request = Box::new(OpenAIRequest {
 733                model: model.full_name().into(),
 734                messages,
 735                stream: true,
 736                stop: vec!["|END|>".to_string()],
 737                temperature,
 738            });
 739
 740            codegen.update(&mut cx, |codegen, cx| codegen.start(request, cx))?;
 741            anyhow::Ok(())
 742        })
 743        .detach();
 744    }
 745
 746    fn update_highlights_for_editor(&self, editor: &View<Editor>, cx: &mut ViewContext<Self>) {
 747        let mut background_ranges = Vec::new();
 748        let mut foreground_ranges = Vec::new();
 749        let empty_inline_assist_ids = Vec::new();
 750        let inline_assist_ids = self
 751            .pending_inline_assist_ids_by_editor
 752            .get(&editor.downgrade())
 753            .unwrap_or(&empty_inline_assist_ids);
 754
 755        for inline_assist_id in inline_assist_ids {
 756            if let Some(pending_assist) = self.pending_inline_assists.get(inline_assist_id) {
 757                let codegen = pending_assist.codegen.read(cx);
 758                background_ranges.push(codegen.range());
 759                foreground_ranges.extend(codegen.last_equal_ranges().iter().cloned());
 760            }
 761        }
 762
 763        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
 764        merge_ranges(&mut background_ranges, &snapshot);
 765        merge_ranges(&mut foreground_ranges, &snapshot);
 766        editor.update(cx, |editor, cx| {
 767            if background_ranges.is_empty() {
 768                editor.clear_background_highlights::<PendingInlineAssist>(cx);
 769            } else {
 770                editor.highlight_background::<PendingInlineAssist>(
 771                    background_ranges,
 772                    |theme| theme.editor_active_line_background, // todo!("use the appropriate color")
 773                    cx,
 774                );
 775            }
 776
 777            if foreground_ranges.is_empty() {
 778                editor.clear_highlights::<PendingInlineAssist>(cx);
 779            } else {
 780                editor.highlight_text::<PendingInlineAssist>(
 781                    foreground_ranges,
 782                    HighlightStyle {
 783                        fade_out: Some(0.6),
 784                        ..Default::default()
 785                    },
 786                    cx,
 787                );
 788            }
 789        });
 790    }
 791
 792    fn new_conversation(&mut self, cx: &mut ViewContext<Self>) -> View<ConversationEditor> {
 793        let editor = cx.new_view(|cx| {
 794            ConversationEditor::new(
 795                self.completion_provider.clone(),
 796                self.languages.clone(),
 797                self.fs.clone(),
 798                self.workspace.clone(),
 799                cx,
 800            )
 801        });
 802        self.add_conversation(editor.clone(), cx);
 803        editor
 804    }
 805
 806    fn add_conversation(&mut self, editor: View<ConversationEditor>, cx: &mut ViewContext<Self>) {
 807        self.subscriptions
 808            .push(cx.subscribe(&editor, Self::handle_conversation_editor_event));
 809
 810        let conversation = editor.read(cx).conversation.clone();
 811        self.subscriptions
 812            .push(cx.observe(&conversation, |_, _, cx| cx.notify()));
 813
 814        let index = self.editors.len();
 815        self.editors.push(editor);
 816        self.set_active_editor_index(Some(index), cx);
 817    }
 818
 819    fn set_active_editor_index(&mut self, index: Option<usize>, cx: &mut ViewContext<Self>) {
 820        self.prev_active_editor_index = self.active_editor_index;
 821        self.active_editor_index = index;
 822        if let Some(editor) = self.active_editor() {
 823            let editor = editor.read(cx).editor.clone();
 824            self.toolbar.update(cx, |toolbar, cx| {
 825                toolbar.set_active_item(Some(&editor), cx);
 826            });
 827            if self.focus_handle.contains_focused(cx) {
 828                cx.focus_view(&editor);
 829            }
 830        } else {
 831            self.toolbar.update(cx, |toolbar, cx| {
 832                toolbar.set_active_item(None, cx);
 833            });
 834        }
 835
 836        cx.notify();
 837    }
 838
 839    fn handle_conversation_editor_event(
 840        &mut self,
 841        _: View<ConversationEditor>,
 842        event: &ConversationEditorEvent,
 843        cx: &mut ViewContext<Self>,
 844    ) {
 845        match event {
 846            ConversationEditorEvent::TabContentChanged => cx.notify(),
 847        }
 848    }
 849
 850    fn save_credentials(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
 851        if let Some(api_key) = self
 852            .api_key_editor
 853            .as_ref()
 854            .map(|editor| editor.read(cx).text(cx))
 855        {
 856            if !api_key.is_empty() {
 857                let credential = ProviderCredential::Credentials {
 858                    api_key: api_key.clone(),
 859                };
 860
 861                self.completion_provider.save_credentials(cx, credential);
 862
 863                self.api_key_editor.take();
 864                self.focus_handle.focus(cx);
 865                cx.notify();
 866            }
 867        } else {
 868            cx.propagate();
 869        }
 870    }
 871
 872    fn reset_credentials(&mut self, _: &ResetKey, cx: &mut ViewContext<Self>) {
 873        self.completion_provider.delete_credentials(cx);
 874        self.api_key_editor = Some(build_api_key_editor(cx));
 875        self.focus_handle.focus(cx);
 876        cx.notify();
 877    }
 878
 879    fn toggle_zoom(&mut self, _: &workspace::ToggleZoom, cx: &mut ViewContext<Self>) {
 880        if self.zoomed {
 881            cx.emit(PanelEvent::ZoomOut)
 882        } else {
 883            cx.emit(PanelEvent::ZoomIn)
 884        }
 885    }
 886
 887    fn deploy(&mut self, action: &search::buffer_search::Deploy, cx: &mut ViewContext<Self>) {
 888        let mut propagate = true;
 889        if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
 890            search_bar.update(cx, |search_bar, cx| {
 891                if search_bar.show(cx) {
 892                    search_bar.search_suggested(cx);
 893                    if action.focus {
 894                        let focus_handle = search_bar.focus_handle(cx);
 895                        search_bar.select_query(cx);
 896                        cx.focus(&focus_handle);
 897                    }
 898                    propagate = false
 899                }
 900            });
 901        }
 902        if propagate {
 903            cx.propagate();
 904        }
 905    }
 906
 907    fn handle_editor_cancel(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
 908        if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
 909            if !search_bar.read(cx).is_dismissed() {
 910                search_bar.update(cx, |search_bar, cx| {
 911                    search_bar.dismiss(&Default::default(), cx)
 912                });
 913                return;
 914            }
 915        }
 916        cx.propagate();
 917    }
 918
 919    fn select_next_match(&mut self, _: &search::SelectNextMatch, cx: &mut ViewContext<Self>) {
 920        if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
 921            search_bar.update(cx, |bar, cx| bar.select_match(Direction::Next, 1, cx));
 922        }
 923    }
 924
 925    fn select_prev_match(&mut self, _: &search::SelectPrevMatch, cx: &mut ViewContext<Self>) {
 926        if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
 927            search_bar.update(cx, |bar, cx| bar.select_match(Direction::Prev, 1, cx));
 928        }
 929    }
 930
 931    fn active_editor(&self) -> Option<&View<ConversationEditor>> {
 932        self.editors.get(self.active_editor_index?)
 933    }
 934
 935    fn render_hamburger_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
 936        IconButton::new("hamburger_button", Icon::Menu)
 937            .on_click(cx.listener(|this, _event, cx| {
 938                if this.active_editor().is_some() {
 939                    this.set_active_editor_index(None, cx);
 940                } else {
 941                    this.set_active_editor_index(this.prev_active_editor_index, cx);
 942                }
 943            }))
 944            .tooltip(|cx| Tooltip::text("Conversation History", cx))
 945    }
 946
 947    fn render_editor_tools(&self, cx: &mut ViewContext<Self>) -> Vec<AnyElement> {
 948        if self.active_editor().is_some() {
 949            vec![
 950                Self::render_split_button(cx).into_any_element(),
 951                Self::render_quote_button(cx).into_any_element(),
 952                Self::render_assist_button(cx).into_any_element(),
 953            ]
 954        } else {
 955            Default::default()
 956        }
 957    }
 958
 959    fn render_split_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
 960        IconButton::new("split_button", Icon::Snip)
 961            .on_click(cx.listener(|this, _event, cx| {
 962                if let Some(active_editor) = this.active_editor() {
 963                    active_editor.update(cx, |editor, cx| editor.split(&Default::default(), cx));
 964                }
 965            }))
 966            .icon_size(IconSize::Small)
 967            .tooltip(|cx| Tooltip::for_action("Split Message", &Split, cx))
 968    }
 969
 970    fn render_assist_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
 971        IconButton::new("assist_button", Icon::MagicWand)
 972            .on_click(cx.listener(|this, _event, cx| {
 973                if let Some(active_editor) = this.active_editor() {
 974                    active_editor.update(cx, |editor, cx| editor.assist(&Default::default(), cx));
 975                }
 976            }))
 977            .icon_size(IconSize::Small)
 978            .tooltip(|cx| Tooltip::for_action("Assist", &Assist, cx))
 979    }
 980
 981    fn render_quote_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
 982        IconButton::new("quote_button", Icon::Quote)
 983            .on_click(cx.listener(|this, _event, cx| {
 984                if let Some(workspace) = this.workspace.upgrade() {
 985                    cx.window_context().defer(move |cx| {
 986                        workspace.update(cx, |workspace, cx| {
 987                            ConversationEditor::quote_selection(workspace, &Default::default(), cx)
 988                        });
 989                    });
 990                }
 991            }))
 992            .icon_size(IconSize::Small)
 993            .tooltip(|cx| Tooltip::for_action("Quote Selection", &QuoteSelection, cx))
 994    }
 995
 996    fn render_plus_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
 997        IconButton::new("plus_button", Icon::Plus)
 998            .on_click(cx.listener(|this, _event, cx| {
 999                this.new_conversation(cx);
1000            }))
1001            .icon_size(IconSize::Small)
1002            .tooltip(|cx| Tooltip::for_action("New Conversation", &NewConversation, cx))
1003    }
1004
1005    fn render_zoom_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1006        let zoomed = self.zoomed;
1007        IconButton::new("zoom_button", Icon::Maximize)
1008            .on_click(cx.listener(|this, _event, cx| {
1009                this.toggle_zoom(&ToggleZoom, cx);
1010            }))
1011            .selected(zoomed)
1012            .selected_icon(Icon::Minimize)
1013            .icon_size(IconSize::Small)
1014            .tooltip(move |cx| {
1015                Tooltip::for_action(if zoomed { "Zoom Out" } else { "Zoom In" }, &ToggleZoom, cx)
1016            })
1017    }
1018
1019    fn render_saved_conversation(
1020        &mut self,
1021        index: usize,
1022        cx: &mut ViewContext<Self>,
1023    ) -> impl IntoElement {
1024        let conversation = &self.saved_conversations[index];
1025        let path = conversation.path.clone();
1026
1027        ButtonLike::new(index)
1028            .on_click(cx.listener(move |this, _, cx| {
1029                this.open_conversation(path.clone(), cx)
1030                    .detach_and_log_err(cx)
1031            }))
1032            .full_width()
1033            .child(
1034                div()
1035                    .flex()
1036                    .w_full()
1037                    .gap_2()
1038                    .child(
1039                        Label::new(conversation.mtime.format("%F %I:%M%p").to_string())
1040                            .color(Color::Muted)
1041                            .size(LabelSize::Small),
1042                    )
1043                    .child(Label::new(conversation.title.clone()).size(LabelSize::Small)),
1044            )
1045    }
1046
1047    fn open_conversation(&mut self, path: PathBuf, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
1048        cx.focus(&self.focus_handle);
1049
1050        if let Some(ix) = self.editor_index_for_path(&path, cx) {
1051            self.set_active_editor_index(Some(ix), cx);
1052            return Task::ready(Ok(()));
1053        }
1054
1055        let fs = self.fs.clone();
1056        let workspace = self.workspace.clone();
1057        let languages = self.languages.clone();
1058        cx.spawn(|this, mut cx| async move {
1059            let saved_conversation = fs.load(&path).await?;
1060            let saved_conversation = serde_json::from_str(&saved_conversation)?;
1061            let conversation = cx.new_model(|cx| {
1062                Conversation::deserialize(saved_conversation, path.clone(), languages, cx)
1063            })?;
1064            this.update(&mut cx, |this, cx| {
1065                // If, by the time we've loaded the conversation, the user has already opened
1066                // the same conversation, we don't want to open it again.
1067                if let Some(ix) = this.editor_index_for_path(&path, cx) {
1068                    this.set_active_editor_index(Some(ix), cx);
1069                } else {
1070                    let editor = cx.new_view(|cx| {
1071                        ConversationEditor::for_conversation(conversation, fs, workspace, cx)
1072                    });
1073                    this.add_conversation(editor, cx);
1074                }
1075            })?;
1076            Ok(())
1077        })
1078    }
1079
1080    fn editor_index_for_path(&self, path: &Path, cx: &AppContext) -> Option<usize> {
1081        self.editors
1082            .iter()
1083            .position(|editor| editor.read(cx).conversation.read(cx).path.as_deref() == Some(path))
1084    }
1085
1086    fn has_credentials(&mut self) -> bool {
1087        self.completion_provider.has_credentials()
1088    }
1089
1090    fn load_credentials(&mut self, cx: &mut ViewContext<Self>) {
1091        self.completion_provider.retrieve_credentials(cx);
1092    }
1093}
1094
1095fn build_api_key_editor(cx: &mut ViewContext<AssistantPanel>) -> View<Editor> {
1096    cx.new_view(|cx| {
1097        let mut editor = Editor::single_line(cx);
1098        editor.set_placeholder_text("sk-000000000000000000000000000000000000000000000000", cx);
1099        editor
1100    })
1101}
1102
1103impl Render for AssistantPanel {
1104    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1105        if let Some(api_key_editor) = self.api_key_editor.clone() {
1106            v_stack()
1107                .on_action(cx.listener(AssistantPanel::save_credentials))
1108                .track_focus(&self.focus_handle)
1109                .child(Label::new(
1110                    "To use the assistant panel or inline assistant, you need to add your OpenAI api key.",
1111                ))
1112                .child(Label::new(
1113                    " - Having a subscription for another service like GitHub Copilot won't work."
1114                ))
1115                .child(Label::new(
1116                    " - You can create a api key at: platform.openai.com/api-keys"
1117                ))
1118                .child(Label::new(
1119                    " "
1120                ))
1121                .child(Label::new(
1122                    "Paste your OpenAI API key and press Enter to use the assistant"
1123                ))
1124                .child(api_key_editor)
1125                .child(Label::new(
1126                    "Click on the Z button in the status bar to close this panel."
1127                ))
1128        } else {
1129            let header = TabBar::new("assistant_header")
1130                .start_child(
1131                    h_stack().gap_1().child(Self::render_hamburger_button(cx)), // .children(title),
1132                )
1133                .children(self.active_editor().map(|editor| {
1134                    h_stack()
1135                        .h(rems(Tab::HEIGHT_IN_REMS))
1136                        .flex_1()
1137                        .px_2()
1138                        .child(Label::new(editor.read(cx).title(cx)).into_element())
1139                }))
1140                .end_child(if self.focus_handle.contains_focused(cx) {
1141                    h_stack()
1142                        .gap_2()
1143                        .child(h_stack().gap_1().children(self.render_editor_tools(cx)))
1144                        .child(
1145                            ui::Divider::vertical()
1146                                .inset()
1147                                .color(ui::DividerColor::Border),
1148                        )
1149                        .child(
1150                            h_stack()
1151                                .gap_1()
1152                                .child(Self::render_plus_button(cx))
1153                                .child(self.render_zoom_button(cx)),
1154                        )
1155                } else {
1156                    div()
1157                });
1158
1159            let contents = if self.active_editor().is_some() {
1160                let mut registrar = DivRegistrar::new(
1161                    |panel, cx| panel.toolbar.read(cx).item_of_type::<BufferSearchBar>(),
1162                    cx,
1163                );
1164                BufferSearchBar::register_inner(&mut registrar);
1165                registrar.into_div()
1166            } else {
1167                div()
1168            };
1169            v_stack()
1170                .key_context("AssistantPanel")
1171                .size_full()
1172                .on_action(cx.listener(|this, _: &workspace::NewFile, cx| {
1173                    this.new_conversation(cx);
1174                }))
1175                .on_action(cx.listener(AssistantPanel::reset_credentials))
1176                .on_action(cx.listener(AssistantPanel::toggle_zoom))
1177                .on_action(cx.listener(AssistantPanel::deploy))
1178                .on_action(cx.listener(AssistantPanel::select_next_match))
1179                .on_action(cx.listener(AssistantPanel::select_prev_match))
1180                .on_action(cx.listener(AssistantPanel::handle_editor_cancel))
1181                .track_focus(&self.focus_handle)
1182                .child(header)
1183                .children(if self.toolbar.read(cx).hidden() {
1184                    None
1185                } else {
1186                    Some(self.toolbar.clone())
1187                })
1188                .child(
1189                    contents
1190                        .flex_1()
1191                        .child(if let Some(editor) = self.active_editor() {
1192                            editor.clone().into_any_element()
1193                        } else {
1194                            let view = cx.view().clone();
1195                            let scroll_handle = self.saved_conversations_scroll_handle.clone();
1196                            let conversation_count = self.saved_conversations.len();
1197                            canvas(move |bounds, cx| {
1198                                uniform_list(
1199                                    view,
1200                                    "saved_conversations",
1201                                    conversation_count,
1202                                    |this, range, cx| {
1203                                        range
1204                                            .map(|ix| this.render_saved_conversation(ix, cx))
1205                                            .collect()
1206                                    },
1207                                )
1208                                .track_scroll(scroll_handle)
1209                                .into_any_element()
1210                                .draw(
1211                                    bounds.origin,
1212                                    bounds.size.map(AvailableSpace::Definite),
1213                                    cx,
1214                                );
1215                            })
1216                            .size_full()
1217                            .into_any_element()
1218                        }),
1219                )
1220        }
1221    }
1222}
1223
1224impl Panel for AssistantPanel {
1225    fn persistent_name() -> &'static str {
1226        "AssistantPanel"
1227    }
1228
1229    fn position(&self, cx: &WindowContext) -> DockPosition {
1230        match AssistantSettings::get_global(cx).dock {
1231            AssistantDockPosition::Left => DockPosition::Left,
1232            AssistantDockPosition::Bottom => DockPosition::Bottom,
1233            AssistantDockPosition::Right => DockPosition::Right,
1234        }
1235    }
1236
1237    fn position_is_valid(&self, _: DockPosition) -> bool {
1238        true
1239    }
1240
1241    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1242        settings::update_settings_file::<AssistantSettings>(self.fs.clone(), cx, move |settings| {
1243            let dock = match position {
1244                DockPosition::Left => AssistantDockPosition::Left,
1245                DockPosition::Bottom => AssistantDockPosition::Bottom,
1246                DockPosition::Right => AssistantDockPosition::Right,
1247            };
1248            settings.dock = Some(dock);
1249        });
1250    }
1251
1252    fn size(&self, cx: &WindowContext) -> Pixels {
1253        let settings = AssistantSettings::get_global(cx);
1254        match self.position(cx) {
1255            DockPosition::Left | DockPosition::Right => {
1256                self.width.unwrap_or_else(|| settings.default_width)
1257            }
1258            DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
1259        }
1260    }
1261
1262    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1263        match self.position(cx) {
1264            DockPosition::Left | DockPosition::Right => self.width = size,
1265            DockPosition::Bottom => self.height = size,
1266        }
1267        cx.notify();
1268    }
1269
1270    fn is_zoomed(&self, _: &WindowContext) -> bool {
1271        self.zoomed
1272    }
1273
1274    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1275        self.zoomed = zoomed;
1276        cx.notify();
1277    }
1278
1279    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1280        if active {
1281            self.load_credentials(cx);
1282
1283            if self.editors.is_empty() {
1284                self.new_conversation(cx);
1285            }
1286        }
1287    }
1288
1289    fn icon(&self, cx: &WindowContext) -> Option<Icon> {
1290        Some(Icon::Ai).filter(|_| AssistantSettings::get_global(cx).button)
1291    }
1292
1293    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1294        Some("Assistant Panel")
1295    }
1296
1297    fn toggle_action(&self) -> Box<dyn Action> {
1298        Box::new(ToggleFocus)
1299    }
1300}
1301
1302impl EventEmitter<PanelEvent> for AssistantPanel {}
1303
1304impl FocusableView for AssistantPanel {
1305    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1306        self.focus_handle.clone()
1307    }
1308}
1309
1310enum ConversationEvent {
1311    MessagesEdited,
1312    SummaryChanged,
1313    StreamedCompletion,
1314}
1315
1316#[derive(Default)]
1317struct Summary {
1318    text: String,
1319    done: bool,
1320}
1321
1322struct Conversation {
1323    id: Option<String>,
1324    buffer: Model<Buffer>,
1325    message_anchors: Vec<MessageAnchor>,
1326    messages_metadata: HashMap<MessageId, MessageMetadata>,
1327    next_message_id: MessageId,
1328    summary: Option<Summary>,
1329    pending_summary: Task<Option<()>>,
1330    completion_count: usize,
1331    pending_completions: Vec<PendingCompletion>,
1332    model: OpenAIModel,
1333    token_count: Option<usize>,
1334    max_token_count: usize,
1335    pending_token_count: Task<Option<()>>,
1336    pending_save: Task<Result<()>>,
1337    path: Option<PathBuf>,
1338    _subscriptions: Vec<Subscription>,
1339    completion_provider: Arc<dyn CompletionProvider>,
1340}
1341
1342impl EventEmitter<ConversationEvent> for Conversation {}
1343
1344impl Conversation {
1345    fn new(
1346        language_registry: Arc<LanguageRegistry>,
1347        cx: &mut ModelContext<Self>,
1348        completion_provider: Arc<dyn CompletionProvider>,
1349    ) -> Self {
1350        let markdown = language_registry.language_for_name("Markdown");
1351        let buffer = cx.new_model(|cx| {
1352            let mut buffer = Buffer::new(0, cx.entity_id().as_u64(), "");
1353            buffer.set_language_registry(language_registry);
1354            cx.spawn(|buffer, mut cx| async move {
1355                let markdown = markdown.await?;
1356                buffer.update(&mut cx, |buffer: &mut Buffer, cx| {
1357                    buffer.set_language(Some(markdown), cx)
1358                })?;
1359                anyhow::Ok(())
1360            })
1361            .detach_and_log_err(cx);
1362            buffer
1363        });
1364
1365        let settings = AssistantSettings::get_global(cx);
1366        let model = settings.default_open_ai_model.clone();
1367
1368        let mut this = Self {
1369            id: Some(Uuid::new_v4().to_string()),
1370            message_anchors: Default::default(),
1371            messages_metadata: Default::default(),
1372            next_message_id: Default::default(),
1373            summary: None,
1374            pending_summary: Task::ready(None),
1375            completion_count: Default::default(),
1376            pending_completions: Default::default(),
1377            token_count: None,
1378            max_token_count: tiktoken_rs::model::get_context_size(&model.full_name()),
1379            pending_token_count: Task::ready(None),
1380            model: model.clone(),
1381            _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
1382            pending_save: Task::ready(Ok(())),
1383            path: None,
1384            buffer,
1385            completion_provider,
1386        };
1387        let message = MessageAnchor {
1388            id: MessageId(post_inc(&mut this.next_message_id.0)),
1389            start: language::Anchor::MIN,
1390        };
1391        this.message_anchors.push(message.clone());
1392        this.messages_metadata.insert(
1393            message.id,
1394            MessageMetadata {
1395                role: Role::User,
1396                sent_at: Local::now(),
1397                status: MessageStatus::Done,
1398            },
1399        );
1400
1401        this.count_remaining_tokens(cx);
1402        this
1403    }
1404
1405    fn serialize(&self, cx: &AppContext) -> SavedConversation {
1406        SavedConversation {
1407            id: self.id.clone(),
1408            zed: "conversation".into(),
1409            version: SavedConversation::VERSION.into(),
1410            text: self.buffer.read(cx).text(),
1411            message_metadata: self.messages_metadata.clone(),
1412            messages: self
1413                .messages(cx)
1414                .map(|message| SavedMessage {
1415                    id: message.id,
1416                    start: message.offset_range.start,
1417                })
1418                .collect(),
1419            summary: self
1420                .summary
1421                .as_ref()
1422                .map(|summary| summary.text.clone())
1423                .unwrap_or_default(),
1424            model: self.model.clone(),
1425        }
1426    }
1427
1428    fn deserialize(
1429        saved_conversation: SavedConversation,
1430        path: PathBuf,
1431        language_registry: Arc<LanguageRegistry>,
1432        cx: &mut ModelContext<Self>,
1433    ) -> Self {
1434        let id = match saved_conversation.id {
1435            Some(id) => Some(id),
1436            None => Some(Uuid::new_v4().to_string()),
1437        };
1438        let model = saved_conversation.model;
1439        let completion_provider: Arc<dyn CompletionProvider> = Arc::new(
1440            OpenAICompletionProvider::new(model.full_name(), cx.background_executor().clone()),
1441        );
1442        completion_provider.retrieve_credentials(cx);
1443        let markdown = language_registry.language_for_name("Markdown");
1444        let mut message_anchors = Vec::new();
1445        let mut next_message_id = MessageId(0);
1446        let buffer = cx.new_model(|cx| {
1447            let mut buffer = Buffer::new(0, cx.entity_id().as_u64(), saved_conversation.text);
1448            for message in saved_conversation.messages {
1449                message_anchors.push(MessageAnchor {
1450                    id: message.id,
1451                    start: buffer.anchor_before(message.start),
1452                });
1453                next_message_id = cmp::max(next_message_id, MessageId(message.id.0 + 1));
1454            }
1455            buffer.set_language_registry(language_registry);
1456            cx.spawn(|buffer, mut cx| async move {
1457                let markdown = markdown.await?;
1458                buffer.update(&mut cx, |buffer: &mut Buffer, cx| {
1459                    buffer.set_language(Some(markdown), cx)
1460                })?;
1461                anyhow::Ok(())
1462            })
1463            .detach_and_log_err(cx);
1464            buffer
1465        });
1466
1467        let mut this = Self {
1468            id,
1469            message_anchors,
1470            messages_metadata: saved_conversation.message_metadata,
1471            next_message_id,
1472            summary: Some(Summary {
1473                text: saved_conversation.summary,
1474                done: true,
1475            }),
1476            pending_summary: Task::ready(None),
1477            completion_count: Default::default(),
1478            pending_completions: Default::default(),
1479            token_count: None,
1480            max_token_count: tiktoken_rs::model::get_context_size(&model.full_name()),
1481            pending_token_count: Task::ready(None),
1482            model,
1483            _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
1484            pending_save: Task::ready(Ok(())),
1485            path: Some(path),
1486            buffer,
1487            completion_provider,
1488        };
1489        this.count_remaining_tokens(cx);
1490        this
1491    }
1492
1493    fn handle_buffer_event(
1494        &mut self,
1495        _: Model<Buffer>,
1496        event: &language::Event,
1497        cx: &mut ModelContext<Self>,
1498    ) {
1499        match event {
1500            language::Event::Edited => {
1501                self.count_remaining_tokens(cx);
1502                cx.emit(ConversationEvent::MessagesEdited);
1503            }
1504            _ => {}
1505        }
1506    }
1507
1508    fn count_remaining_tokens(&mut self, cx: &mut ModelContext<Self>) {
1509        let messages = self
1510            .messages(cx)
1511            .into_iter()
1512            .filter_map(|message| {
1513                Some(tiktoken_rs::ChatCompletionRequestMessage {
1514                    role: match message.role {
1515                        Role::User => "user".into(),
1516                        Role::Assistant => "assistant".into(),
1517                        Role::System => "system".into(),
1518                    },
1519                    content: Some(
1520                        self.buffer
1521                            .read(cx)
1522                            .text_for_range(message.offset_range)
1523                            .collect(),
1524                    ),
1525                    name: None,
1526                    function_call: None,
1527                })
1528            })
1529            .collect::<Vec<_>>();
1530        let model = self.model.clone();
1531        self.pending_token_count = cx.spawn(|this, mut cx| {
1532            async move {
1533                cx.background_executor()
1534                    .timer(Duration::from_millis(200))
1535                    .await;
1536                let token_count = cx
1537                    .background_executor()
1538                    .spawn(async move {
1539                        tiktoken_rs::num_tokens_from_messages(&model.full_name(), &messages)
1540                    })
1541                    .await?;
1542
1543                this.update(&mut cx, |this, cx| {
1544                    this.max_token_count =
1545                        tiktoken_rs::model::get_context_size(&this.model.full_name());
1546                    this.token_count = Some(token_count);
1547                    cx.notify()
1548                })?;
1549                anyhow::Ok(())
1550            }
1551            .log_err()
1552        });
1553    }
1554
1555    fn remaining_tokens(&self) -> Option<isize> {
1556        Some(self.max_token_count as isize - self.token_count? as isize)
1557    }
1558
1559    fn set_model(&mut self, model: OpenAIModel, cx: &mut ModelContext<Self>) {
1560        self.model = model;
1561        self.count_remaining_tokens(cx);
1562        cx.notify();
1563    }
1564
1565    fn assist(
1566        &mut self,
1567        selected_messages: HashSet<MessageId>,
1568        cx: &mut ModelContext<Self>,
1569    ) -> Vec<MessageAnchor> {
1570        let mut user_messages = Vec::new();
1571
1572        let last_message_id = if let Some(last_message_id) =
1573            self.message_anchors.iter().rev().find_map(|message| {
1574                message
1575                    .start
1576                    .is_valid(self.buffer.read(cx))
1577                    .then_some(message.id)
1578            }) {
1579            last_message_id
1580        } else {
1581            return Default::default();
1582        };
1583
1584        let mut should_assist = false;
1585        for selected_message_id in selected_messages {
1586            let selected_message_role =
1587                if let Some(metadata) = self.messages_metadata.get(&selected_message_id) {
1588                    metadata.role
1589                } else {
1590                    continue;
1591                };
1592
1593            if selected_message_role == Role::Assistant {
1594                if let Some(user_message) = self.insert_message_after(
1595                    selected_message_id,
1596                    Role::User,
1597                    MessageStatus::Done,
1598                    cx,
1599                ) {
1600                    user_messages.push(user_message);
1601                }
1602            } else {
1603                should_assist = true;
1604            }
1605        }
1606
1607        if should_assist {
1608            if !self.completion_provider.has_credentials() {
1609                return Default::default();
1610            }
1611
1612            let request: Box<dyn CompletionRequest> = Box::new(OpenAIRequest {
1613                model: self.model.full_name().to_string(),
1614                messages: self
1615                    .messages(cx)
1616                    .filter(|message| matches!(message.status, MessageStatus::Done))
1617                    .map(|message| message.to_open_ai_message(self.buffer.read(cx)))
1618                    .collect(),
1619                stream: true,
1620                stop: vec![],
1621                temperature: 1.0,
1622            });
1623
1624            let stream = self.completion_provider.complete(request);
1625            let assistant_message = self
1626                .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1627                .unwrap();
1628
1629            // Queue up the user's next reply.
1630            let user_message = self
1631                .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
1632                .unwrap();
1633            user_messages.push(user_message);
1634
1635            let task = cx.spawn({
1636                |this, mut cx| async move {
1637                    let assistant_message_id = assistant_message.id;
1638                    let stream_completion = async {
1639                        let mut messages = stream.await?;
1640
1641                        while let Some(message) = messages.next().await {
1642                            let text = message?;
1643
1644                            this.update(&mut cx, |this, cx| {
1645                                let message_ix = this
1646                                    .message_anchors
1647                                    .iter()
1648                                    .position(|message| message.id == assistant_message_id)?;
1649                                this.buffer.update(cx, |buffer, cx| {
1650                                    let offset = this.message_anchors[message_ix + 1..]
1651                                        .iter()
1652                                        .find(|message| message.start.is_valid(buffer))
1653                                        .map_or(buffer.len(), |message| {
1654                                            message.start.to_offset(buffer).saturating_sub(1)
1655                                        });
1656                                    buffer.edit([(offset..offset, text)], None, cx);
1657                                });
1658                                cx.emit(ConversationEvent::StreamedCompletion);
1659
1660                                Some(())
1661                            })?;
1662                            smol::future::yield_now().await;
1663                        }
1664
1665                        this.update(&mut cx, |this, cx| {
1666                            this.pending_completions
1667                                .retain(|completion| completion.id != this.completion_count);
1668                            this.summarize(cx);
1669                        })?;
1670
1671                        anyhow::Ok(())
1672                    };
1673
1674                    let result = stream_completion.await;
1675
1676                    this.update(&mut cx, |this, cx| {
1677                        if let Some(metadata) =
1678                            this.messages_metadata.get_mut(&assistant_message.id)
1679                        {
1680                            match result {
1681                                Ok(_) => {
1682                                    metadata.status = MessageStatus::Done;
1683                                }
1684                                Err(error) => {
1685                                    metadata.status = MessageStatus::Error(SharedString::from(
1686                                        error.to_string().trim().to_string(),
1687                                    ));
1688                                }
1689                            }
1690                            cx.notify();
1691                        }
1692                    })
1693                    .ok();
1694                }
1695            });
1696
1697            self.pending_completions.push(PendingCompletion {
1698                id: post_inc(&mut self.completion_count),
1699                _task: task,
1700            });
1701        }
1702
1703        user_messages
1704    }
1705
1706    fn cancel_last_assist(&mut self) -> bool {
1707        self.pending_completions.pop().is_some()
1708    }
1709
1710    fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
1711        for id in ids {
1712            if let Some(metadata) = self.messages_metadata.get_mut(&id) {
1713                metadata.role.cycle();
1714                cx.emit(ConversationEvent::MessagesEdited);
1715                cx.notify();
1716            }
1717        }
1718    }
1719
1720    fn insert_message_after(
1721        &mut self,
1722        message_id: MessageId,
1723        role: Role,
1724        status: MessageStatus,
1725        cx: &mut ModelContext<Self>,
1726    ) -> Option<MessageAnchor> {
1727        if let Some(prev_message_ix) = self
1728            .message_anchors
1729            .iter()
1730            .position(|message| message.id == message_id)
1731        {
1732            // Find the next valid message after the one we were given.
1733            let mut next_message_ix = prev_message_ix + 1;
1734            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
1735                if next_message.start.is_valid(self.buffer.read(cx)) {
1736                    break;
1737                }
1738                next_message_ix += 1;
1739            }
1740
1741            let start = self.buffer.update(cx, |buffer, cx| {
1742                let offset = self
1743                    .message_anchors
1744                    .get(next_message_ix)
1745                    .map_or(buffer.len(), |message| message.start.to_offset(buffer) - 1);
1746                buffer.edit([(offset..offset, "\n")], None, cx);
1747                buffer.anchor_before(offset + 1)
1748            });
1749            let message = MessageAnchor {
1750                id: MessageId(post_inc(&mut self.next_message_id.0)),
1751                start,
1752            };
1753            self.message_anchors
1754                .insert(next_message_ix, message.clone());
1755            self.messages_metadata.insert(
1756                message.id,
1757                MessageMetadata {
1758                    role,
1759                    sent_at: Local::now(),
1760                    status,
1761                },
1762            );
1763            cx.emit(ConversationEvent::MessagesEdited);
1764            Some(message)
1765        } else {
1766            None
1767        }
1768    }
1769
1770    fn split_message(
1771        &mut self,
1772        range: Range<usize>,
1773        cx: &mut ModelContext<Self>,
1774    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
1775        let start_message = self.message_for_offset(range.start, cx);
1776        let end_message = self.message_for_offset(range.end, cx);
1777        if let Some((start_message, end_message)) = start_message.zip(end_message) {
1778            // Prevent splitting when range spans multiple messages.
1779            if start_message.id != end_message.id {
1780                return (None, None);
1781            }
1782
1783            let message = start_message;
1784            let role = message.role;
1785            let mut edited_buffer = false;
1786
1787            let mut suffix_start = None;
1788            if range.start > message.offset_range.start && range.end < message.offset_range.end - 1
1789            {
1790                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
1791                    suffix_start = Some(range.end + 1);
1792                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
1793                    suffix_start = Some(range.end);
1794                }
1795            }
1796
1797            let suffix = if let Some(suffix_start) = suffix_start {
1798                MessageAnchor {
1799                    id: MessageId(post_inc(&mut self.next_message_id.0)),
1800                    start: self.buffer.read(cx).anchor_before(suffix_start),
1801                }
1802            } else {
1803                self.buffer.update(cx, |buffer, cx| {
1804                    buffer.edit([(range.end..range.end, "\n")], None, cx);
1805                });
1806                edited_buffer = true;
1807                MessageAnchor {
1808                    id: MessageId(post_inc(&mut self.next_message_id.0)),
1809                    start: self.buffer.read(cx).anchor_before(range.end + 1),
1810                }
1811            };
1812
1813            self.message_anchors
1814                .insert(message.index_range.end + 1, suffix.clone());
1815            self.messages_metadata.insert(
1816                suffix.id,
1817                MessageMetadata {
1818                    role,
1819                    sent_at: Local::now(),
1820                    status: MessageStatus::Done,
1821                },
1822            );
1823
1824            let new_messages =
1825                if range.start == range.end || range.start == message.offset_range.start {
1826                    (None, Some(suffix))
1827                } else {
1828                    let mut prefix_end = None;
1829                    if range.start > message.offset_range.start
1830                        && range.end < message.offset_range.end - 1
1831                    {
1832                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
1833                            prefix_end = Some(range.start + 1);
1834                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
1835                            == Some('\n')
1836                        {
1837                            prefix_end = Some(range.start);
1838                        }
1839                    }
1840
1841                    let selection = if let Some(prefix_end) = prefix_end {
1842                        cx.emit(ConversationEvent::MessagesEdited);
1843                        MessageAnchor {
1844                            id: MessageId(post_inc(&mut self.next_message_id.0)),
1845                            start: self.buffer.read(cx).anchor_before(prefix_end),
1846                        }
1847                    } else {
1848                        self.buffer.update(cx, |buffer, cx| {
1849                            buffer.edit([(range.start..range.start, "\n")], None, cx)
1850                        });
1851                        edited_buffer = true;
1852                        MessageAnchor {
1853                            id: MessageId(post_inc(&mut self.next_message_id.0)),
1854                            start: self.buffer.read(cx).anchor_before(range.end + 1),
1855                        }
1856                    };
1857
1858                    self.message_anchors
1859                        .insert(message.index_range.end + 1, selection.clone());
1860                    self.messages_metadata.insert(
1861                        selection.id,
1862                        MessageMetadata {
1863                            role,
1864                            sent_at: Local::now(),
1865                            status: MessageStatus::Done,
1866                        },
1867                    );
1868                    (Some(selection), Some(suffix))
1869                };
1870
1871            if !edited_buffer {
1872                cx.emit(ConversationEvent::MessagesEdited);
1873            }
1874            new_messages
1875        } else {
1876            (None, None)
1877        }
1878    }
1879
1880    fn summarize(&mut self, cx: &mut ModelContext<Self>) {
1881        if self.message_anchors.len() >= 2 && self.summary.is_none() {
1882            if !self.completion_provider.has_credentials() {
1883                return;
1884            }
1885
1886            let messages = self
1887                .messages(cx)
1888                .take(2)
1889                .map(|message| message.to_open_ai_message(self.buffer.read(cx)))
1890                .chain(Some(RequestMessage {
1891                    role: Role::User,
1892                    content: "Summarize the conversation into a short title without punctuation"
1893                        .into(),
1894                }));
1895            let request: Box<dyn CompletionRequest> = Box::new(OpenAIRequest {
1896                model: self.model.full_name().to_string(),
1897                messages: messages.collect(),
1898                stream: true,
1899                stop: vec![],
1900                temperature: 1.0,
1901            });
1902
1903            let stream = self.completion_provider.complete(request);
1904            self.pending_summary = cx.spawn(|this, mut cx| {
1905                async move {
1906                    let mut messages = stream.await?;
1907
1908                    while let Some(message) = messages.next().await {
1909                        let text = message?;
1910                        this.update(&mut cx, |this, cx| {
1911                            this.summary
1912                                .get_or_insert(Default::default())
1913                                .text
1914                                .push_str(&text);
1915                            cx.emit(ConversationEvent::SummaryChanged);
1916                        })?;
1917                    }
1918
1919                    this.update(&mut cx, |this, cx| {
1920                        if let Some(summary) = this.summary.as_mut() {
1921                            summary.done = true;
1922                            cx.emit(ConversationEvent::SummaryChanged);
1923                        }
1924                    })?;
1925
1926                    anyhow::Ok(())
1927                }
1928                .log_err()
1929            });
1930        }
1931    }
1932
1933    fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
1934        self.messages_for_offsets([offset], cx).pop()
1935    }
1936
1937    fn messages_for_offsets(
1938        &self,
1939        offsets: impl IntoIterator<Item = usize>,
1940        cx: &AppContext,
1941    ) -> Vec<Message> {
1942        let mut result = Vec::new();
1943
1944        let mut messages = self.messages(cx).peekable();
1945        let mut offsets = offsets.into_iter().peekable();
1946        let mut current_message = messages.next();
1947        while let Some(offset) = offsets.next() {
1948            // Locate the message that contains the offset.
1949            while current_message.as_ref().map_or(false, |message| {
1950                !message.offset_range.contains(&offset) && messages.peek().is_some()
1951            }) {
1952                current_message = messages.next();
1953            }
1954            let Some(message) = current_message.as_ref() else {
1955                break;
1956            };
1957
1958            // Skip offsets that are in the same message.
1959            while offsets.peek().map_or(false, |offset| {
1960                message.offset_range.contains(offset) || messages.peek().is_none()
1961            }) {
1962                offsets.next();
1963            }
1964
1965            result.push(message.clone());
1966        }
1967        result
1968    }
1969
1970    fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
1971        let buffer = self.buffer.read(cx);
1972        let mut message_anchors = self.message_anchors.iter().enumerate().peekable();
1973        iter::from_fn(move || {
1974            while let Some((start_ix, message_anchor)) = message_anchors.next() {
1975                let metadata = self.messages_metadata.get(&message_anchor.id)?;
1976                let message_start = message_anchor.start.to_offset(buffer);
1977                let mut message_end = None;
1978                let mut end_ix = start_ix;
1979                while let Some((_, next_message)) = message_anchors.peek() {
1980                    if next_message.start.is_valid(buffer) {
1981                        message_end = Some(next_message.start);
1982                        break;
1983                    } else {
1984                        end_ix += 1;
1985                        message_anchors.next();
1986                    }
1987                }
1988                let message_end = message_end
1989                    .unwrap_or(language::Anchor::MAX)
1990                    .to_offset(buffer);
1991                return Some(Message {
1992                    index_range: start_ix..end_ix,
1993                    offset_range: message_start..message_end,
1994                    id: message_anchor.id,
1995                    anchor: message_anchor.start,
1996                    role: metadata.role,
1997                    sent_at: metadata.sent_at,
1998                    status: metadata.status.clone(),
1999                });
2000            }
2001            None
2002        })
2003    }
2004
2005    fn save(
2006        &mut self,
2007        debounce: Option<Duration>,
2008        fs: Arc<dyn Fs>,
2009        cx: &mut ModelContext<Conversation>,
2010    ) {
2011        self.pending_save = cx.spawn(|this, mut cx| async move {
2012            if let Some(debounce) = debounce {
2013                cx.background_executor().timer(debounce).await;
2014            }
2015
2016            let (old_path, summary) = this.read_with(&cx, |this, _| {
2017                let path = this.path.clone();
2018                let summary = if let Some(summary) = this.summary.as_ref() {
2019                    if summary.done {
2020                        Some(summary.text.clone())
2021                    } else {
2022                        None
2023                    }
2024                } else {
2025                    None
2026                };
2027                (path, summary)
2028            })?;
2029
2030            if let Some(summary) = summary {
2031                let conversation = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2032                let path = if let Some(old_path) = old_path {
2033                    old_path
2034                } else {
2035                    let mut discriminant = 1;
2036                    let mut new_path;
2037                    loop {
2038                        new_path = CONVERSATIONS_DIR.join(&format!(
2039                            "{} - {}.zed.json",
2040                            summary.trim(),
2041                            discriminant
2042                        ));
2043                        if fs.is_file(&new_path).await {
2044                            discriminant += 1;
2045                        } else {
2046                            break;
2047                        }
2048                    }
2049                    new_path
2050                };
2051
2052                fs.create_dir(CONVERSATIONS_DIR.as_ref()).await?;
2053                fs.atomic_write(path.clone(), serde_json::to_string(&conversation).unwrap())
2054                    .await?;
2055                this.update(&mut cx, |this, _| this.path = Some(path))?;
2056            }
2057
2058            Ok(())
2059        });
2060    }
2061}
2062
2063struct PendingCompletion {
2064    id: usize,
2065    _task: Task<()>,
2066}
2067
2068enum ConversationEditorEvent {
2069    TabContentChanged,
2070}
2071
2072#[derive(Copy, Clone, Debug, PartialEq)]
2073struct ScrollPosition {
2074    offset_before_cursor: gpui::Point<f32>,
2075    cursor: Anchor,
2076}
2077
2078struct ConversationEditor {
2079    conversation: Model<Conversation>,
2080    fs: Arc<dyn Fs>,
2081    workspace: WeakView<Workspace>,
2082    editor: View<Editor>,
2083    blocks: HashSet<BlockId>,
2084    scroll_position: Option<ScrollPosition>,
2085    _subscriptions: Vec<Subscription>,
2086}
2087
2088impl ConversationEditor {
2089    fn new(
2090        completion_provider: Arc<dyn CompletionProvider>,
2091        language_registry: Arc<LanguageRegistry>,
2092        fs: Arc<dyn Fs>,
2093        workspace: WeakView<Workspace>,
2094        cx: &mut ViewContext<Self>,
2095    ) -> Self {
2096        let conversation =
2097            cx.new_model(|cx| Conversation::new(language_registry, cx, completion_provider));
2098        Self::for_conversation(conversation, fs, workspace, cx)
2099    }
2100
2101    fn for_conversation(
2102        conversation: Model<Conversation>,
2103        fs: Arc<dyn Fs>,
2104        workspace: WeakView<Workspace>,
2105        cx: &mut ViewContext<Self>,
2106    ) -> Self {
2107        let editor = cx.new_view(|cx| {
2108            let mut editor = Editor::for_buffer(conversation.read(cx).buffer.clone(), None, cx);
2109            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
2110            editor.set_show_gutter(false, cx);
2111            editor.set_show_wrap_guides(false, cx);
2112            editor
2113        });
2114
2115        let _subscriptions = vec![
2116            cx.observe(&conversation, |_, _, cx| cx.notify()),
2117            cx.subscribe(&conversation, Self::handle_conversation_event),
2118            cx.subscribe(&editor, Self::handle_editor_event),
2119        ];
2120
2121        let mut this = Self {
2122            conversation,
2123            editor,
2124            blocks: Default::default(),
2125            scroll_position: None,
2126            fs,
2127            workspace,
2128            _subscriptions,
2129        };
2130        this.update_message_headers(cx);
2131        this
2132    }
2133
2134    fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
2135        report_assistant_event(
2136            self.workspace.clone(),
2137            self.conversation.read(cx).id.clone(),
2138            AssistantKind::Panel,
2139            cx,
2140        );
2141
2142        let cursors = self.cursors(cx);
2143
2144        let user_messages = self.conversation.update(cx, |conversation, cx| {
2145            let selected_messages = conversation
2146                .messages_for_offsets(cursors, cx)
2147                .into_iter()
2148                .map(|message| message.id)
2149                .collect();
2150            conversation.assist(selected_messages, cx)
2151        });
2152        let new_selections = user_messages
2153            .iter()
2154            .map(|message| {
2155                let cursor = message
2156                    .start
2157                    .to_offset(self.conversation.read(cx).buffer.read(cx));
2158                cursor..cursor
2159            })
2160            .collect::<Vec<_>>();
2161        if !new_selections.is_empty() {
2162            self.editor.update(cx, |editor, cx| {
2163                editor.change_selections(
2164                    Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
2165                    cx,
2166                    |selections| selections.select_ranges(new_selections),
2167                );
2168            });
2169            // Avoid scrolling to the new cursor position so the assistant's output is stable.
2170            cx.defer(|this, _| this.scroll_position = None);
2171        }
2172    }
2173
2174    fn cancel_last_assist(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
2175        if !self
2176            .conversation
2177            .update(cx, |conversation, _| conversation.cancel_last_assist())
2178        {
2179            cx.propagate();
2180        }
2181    }
2182
2183    fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
2184        let cursors = self.cursors(cx);
2185        self.conversation.update(cx, |conversation, cx| {
2186            let messages = conversation
2187                .messages_for_offsets(cursors, cx)
2188                .into_iter()
2189                .map(|message| message.id)
2190                .collect();
2191            conversation.cycle_message_roles(messages, cx)
2192        });
2193    }
2194
2195    fn cursors(&self, cx: &AppContext) -> Vec<usize> {
2196        let selections = self.editor.read(cx).selections.all::<usize>(cx);
2197        selections
2198            .into_iter()
2199            .map(|selection| selection.head())
2200            .collect()
2201    }
2202
2203    fn handle_conversation_event(
2204        &mut self,
2205        _: Model<Conversation>,
2206        event: &ConversationEvent,
2207        cx: &mut ViewContext<Self>,
2208    ) {
2209        match event {
2210            ConversationEvent::MessagesEdited => {
2211                self.update_message_headers(cx);
2212                self.conversation.update(cx, |conversation, cx| {
2213                    conversation.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
2214                });
2215            }
2216            ConversationEvent::SummaryChanged => {
2217                cx.emit(ConversationEditorEvent::TabContentChanged);
2218                self.conversation.update(cx, |conversation, cx| {
2219                    conversation.save(None, self.fs.clone(), cx);
2220                });
2221            }
2222            ConversationEvent::StreamedCompletion => {
2223                self.editor.update(cx, |editor, cx| {
2224                    if let Some(scroll_position) = self.scroll_position {
2225                        let snapshot = editor.snapshot(cx);
2226                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
2227                        let scroll_top =
2228                            cursor_point.row() as f32 - scroll_position.offset_before_cursor.y;
2229                        editor.set_scroll_position(
2230                            point(scroll_position.offset_before_cursor.x, scroll_top),
2231                            cx,
2232                        );
2233                    }
2234                });
2235            }
2236        }
2237    }
2238
2239    fn handle_editor_event(
2240        &mut self,
2241        _: View<Editor>,
2242        event: &EditorEvent,
2243        cx: &mut ViewContext<Self>,
2244    ) {
2245        match event {
2246            EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2247                let cursor_scroll_position = self.cursor_scroll_position(cx);
2248                if *autoscroll {
2249                    self.scroll_position = cursor_scroll_position;
2250                } else if self.scroll_position != cursor_scroll_position {
2251                    self.scroll_position = None;
2252                }
2253            }
2254            EditorEvent::SelectionsChanged { .. } => {
2255                self.scroll_position = self.cursor_scroll_position(cx);
2256            }
2257            _ => {}
2258        }
2259    }
2260
2261    fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2262        self.editor.update(cx, |editor, cx| {
2263            let snapshot = editor.snapshot(cx);
2264            let cursor = editor.selections.newest_anchor().head();
2265            let cursor_row = cursor.to_display_point(&snapshot.display_snapshot).row() as f32;
2266            let scroll_position = editor
2267                .scroll_manager
2268                .anchor()
2269                .scroll_position(&snapshot.display_snapshot);
2270
2271            let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2272            if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2273                Some(ScrollPosition {
2274                    cursor,
2275                    offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2276                })
2277            } else {
2278                None
2279            }
2280        })
2281    }
2282
2283    fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2284        self.editor.update(cx, |editor, cx| {
2285            let buffer = editor.buffer().read(cx).snapshot(cx);
2286            let excerpt_id = *buffer.as_singleton().unwrap().0;
2287            let old_blocks = std::mem::take(&mut self.blocks);
2288            let new_blocks = self
2289                .conversation
2290                .read(cx)
2291                .messages(cx)
2292                .map(|message| BlockProperties {
2293                    position: buffer.anchor_in_excerpt(excerpt_id, message.anchor),
2294                    height: 2,
2295                    style: BlockStyle::Sticky,
2296                    render: Arc::new({
2297                        let conversation = self.conversation.clone();
2298                        move |_cx| {
2299                            let message_id = message.id;
2300                            let sender = ButtonLike::new("role")
2301                                .child(match message.role {
2302                                    Role::User => Label::new("You").color(Color::Default),
2303                                    Role::Assistant => {
2304                                        Label::new("Assistant").color(Color::Modified)
2305                                    }
2306                                    Role::System => Label::new("System").color(Color::Warning),
2307                                })
2308                                .tooltip(|cx| {
2309                                    Tooltip::with_meta(
2310                                        "Toggle message role",
2311                                        None,
2312                                        "Available roles: You (User), Assistant, System",
2313                                        cx,
2314                                    )
2315                                })
2316                                .on_click({
2317                                    let conversation = conversation.clone();
2318                                    move |_, cx| {
2319                                        conversation.update(cx, |conversation, cx| {
2320                                            conversation.cycle_message_roles(
2321                                                HashSet::from_iter(Some(message_id)),
2322                                                cx,
2323                                            )
2324                                        })
2325                                    }
2326                                });
2327
2328                            div()
2329                                .h_flex()
2330                                .id(("message_header", message_id.0))
2331                                .h_11()
2332                                .relative()
2333                                .gap_1()
2334                                // Sender is a button with a padding of 1, but only has a background on hover,
2335                                // so we shift it left by the same amount to align the text with the content
2336                                // in the un-hovered state.
2337                                .child(div().child(sender).relative().neg_left_1())
2338                                // TODO: Only show this if the message if the message has been sent
2339                                .child(
2340                                    Label::new(
2341                                        FormatDistance::from_now(DateTimeType::Local(
2342                                            message.sent_at,
2343                                        ))
2344                                        .hide_prefix(true)
2345                                        .add_suffix(true)
2346                                        .to_string(),
2347                                    )
2348                                    .color(Color::Muted),
2349                                )
2350                                .children(
2351                                    if let MessageStatus::Error(error) = message.status.clone() {
2352                                        Some(
2353                                            div()
2354                                                .id("error")
2355                                                .tooltip(move |cx| Tooltip::text(error.clone(), cx))
2356                                                .child(IconElement::new(Icon::XCircle)),
2357                                        )
2358                                    } else {
2359                                        None
2360                                    },
2361                                )
2362                                .into_any_element()
2363                        }
2364                    }),
2365                    disposition: BlockDisposition::Above,
2366                })
2367                .collect::<Vec<_>>();
2368
2369            editor.remove_blocks(old_blocks, None, cx);
2370            let ids = editor.insert_blocks(new_blocks, None, cx);
2371            self.blocks = HashSet::from_iter(ids);
2372        });
2373    }
2374
2375    fn quote_selection(
2376        workspace: &mut Workspace,
2377        _: &QuoteSelection,
2378        cx: &mut ViewContext<Workspace>,
2379    ) {
2380        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2381            return;
2382        };
2383        let Some(editor) = workspace
2384            .active_item(cx)
2385            .and_then(|item| item.act_as::<Editor>(cx))
2386        else {
2387            return;
2388        };
2389
2390        let editor = editor.read(cx);
2391        let range = editor.selections.newest::<usize>(cx).range();
2392        let buffer = editor.buffer().read(cx).snapshot(cx);
2393        let start_language = buffer.language_at(range.start);
2394        let end_language = buffer.language_at(range.end);
2395        let language_name = if start_language == end_language {
2396            start_language.map(|language| language.name())
2397        } else {
2398            None
2399        };
2400        let language_name = language_name.as_deref().unwrap_or("").to_lowercase();
2401
2402        let selected_text = buffer.text_for_range(range).collect::<String>();
2403        let text = if selected_text.is_empty() {
2404            None
2405        } else {
2406            Some(if language_name == "markdown" {
2407                selected_text
2408                    .lines()
2409                    .map(|line| format!("> {}", line))
2410                    .collect::<Vec<_>>()
2411                    .join("\n")
2412            } else {
2413                format!("```{language_name}\n{selected_text}\n```")
2414            })
2415        };
2416
2417        // Activate the panel
2418        if !panel.focus_handle(cx).contains_focused(cx) {
2419            workspace.toggle_panel_focus::<AssistantPanel>(cx);
2420        }
2421
2422        if let Some(text) = text {
2423            panel.update(cx, |panel, cx| {
2424                let conversation = panel
2425                    .active_editor()
2426                    .cloned()
2427                    .unwrap_or_else(|| panel.new_conversation(cx));
2428                conversation.update(cx, |conversation, cx| {
2429                    conversation
2430                        .editor
2431                        .update(cx, |editor, cx| editor.insert(&text, cx))
2432                });
2433            });
2434        }
2435    }
2436
2437    fn copy(&mut self, _: &editor::Copy, cx: &mut ViewContext<Self>) {
2438        let editor = self.editor.read(cx);
2439        let conversation = self.conversation.read(cx);
2440        if editor.selections.count() == 1 {
2441            let selection = editor.selections.newest::<usize>(cx);
2442            let mut copied_text = String::new();
2443            let mut spanned_messages = 0;
2444            for message in conversation.messages(cx) {
2445                if message.offset_range.start >= selection.range().end {
2446                    break;
2447                } else if message.offset_range.end >= selection.range().start {
2448                    let range = cmp::max(message.offset_range.start, selection.range().start)
2449                        ..cmp::min(message.offset_range.end, selection.range().end);
2450                    if !range.is_empty() {
2451                        spanned_messages += 1;
2452                        write!(&mut copied_text, "## {}\n\n", message.role).unwrap();
2453                        for chunk in conversation.buffer.read(cx).text_for_range(range) {
2454                            copied_text.push_str(&chunk);
2455                        }
2456                        copied_text.push('\n');
2457                    }
2458                }
2459            }
2460
2461            if spanned_messages > 1 {
2462                cx.write_to_clipboard(ClipboardItem::new(copied_text));
2463                return;
2464            }
2465        }
2466
2467        cx.propagate();
2468    }
2469
2470    fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
2471        self.conversation.update(cx, |conversation, cx| {
2472            let selections = self.editor.read(cx).selections.disjoint_anchors();
2473            for selection in selections.into_iter() {
2474                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2475                let range = selection
2476                    .map(|endpoint| endpoint.to_offset(&buffer))
2477                    .range();
2478                conversation.split_message(range, cx);
2479            }
2480        });
2481    }
2482
2483    fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
2484        self.conversation.update(cx, |conversation, cx| {
2485            conversation.save(None, self.fs.clone(), cx)
2486        });
2487    }
2488
2489    fn cycle_model(&mut self, cx: &mut ViewContext<Self>) {
2490        self.conversation.update(cx, |conversation, cx| {
2491            let new_model = conversation.model.cycle();
2492            conversation.set_model(new_model, cx);
2493        });
2494    }
2495
2496    fn title(&self, cx: &AppContext) -> String {
2497        self.conversation
2498            .read(cx)
2499            .summary
2500            .as_ref()
2501            .map(|summary| summary.text.clone())
2502            .unwrap_or_else(|| "New Conversation".into())
2503    }
2504
2505    fn render_current_model(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2506        Button::new(
2507            "current_model",
2508            self.conversation.read(cx).model.short_name(),
2509        )
2510        .style(ButtonStyle::Filled)
2511        .tooltip(move |cx| Tooltip::text("Change Model", cx))
2512        .on_click(cx.listener(|this, _, cx| this.cycle_model(cx)))
2513    }
2514
2515    fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
2516        let remaining_tokens = self.conversation.read(cx).remaining_tokens()?;
2517        let remaining_tokens_color = if remaining_tokens <= 0 {
2518            Color::Error
2519        } else if remaining_tokens <= 500 {
2520            Color::Warning
2521        } else {
2522            Color::Default
2523        };
2524        Some(Label::new(remaining_tokens.to_string()).color(remaining_tokens_color))
2525    }
2526}
2527
2528impl EventEmitter<ConversationEditorEvent> for ConversationEditor {}
2529
2530impl Render for ConversationEditor {
2531    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
2532        div()
2533            .key_context("ConversationEditor")
2534            .capture_action(cx.listener(ConversationEditor::cancel_last_assist))
2535            .capture_action(cx.listener(ConversationEditor::save))
2536            .capture_action(cx.listener(ConversationEditor::copy))
2537            .capture_action(cx.listener(ConversationEditor::cycle_message_role))
2538            .on_action(cx.listener(ConversationEditor::assist))
2539            .on_action(cx.listener(ConversationEditor::split))
2540            .size_full()
2541            .relative()
2542            .child(
2543                div()
2544                    .size_full()
2545                    .pl_4()
2546                    .bg(cx.theme().colors().editor_background)
2547                    .child(self.editor.clone()),
2548            )
2549            .child(
2550                h_stack()
2551                    .absolute()
2552                    .gap_1()
2553                    .top_3()
2554                    .right_5()
2555                    .child(self.render_current_model(cx))
2556                    .children(self.render_remaining_tokens(cx)),
2557            )
2558    }
2559}
2560
2561impl FocusableView for ConversationEditor {
2562    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
2563        self.editor.focus_handle(cx)
2564    }
2565}
2566
2567#[derive(Clone, Debug)]
2568struct MessageAnchor {
2569    id: MessageId,
2570    start: language::Anchor,
2571}
2572
2573#[derive(Clone, Debug)]
2574pub struct Message {
2575    offset_range: Range<usize>,
2576    index_range: Range<usize>,
2577    id: MessageId,
2578    anchor: language::Anchor,
2579    role: Role,
2580    sent_at: DateTime<Local>,
2581    status: MessageStatus,
2582}
2583
2584impl Message {
2585    fn to_open_ai_message(&self, buffer: &Buffer) -> RequestMessage {
2586        let content = buffer
2587            .text_for_range(self.offset_range.clone())
2588            .collect::<String>();
2589        RequestMessage {
2590            role: self.role,
2591            content: content.trim_end().into(),
2592        }
2593    }
2594}
2595
2596enum InlineAssistantEvent {
2597    Confirmed {
2598        prompt: String,
2599        include_conversation: bool,
2600        retrieve_context: bool,
2601    },
2602    Canceled,
2603    Dismissed,
2604    IncludeConversationToggled {
2605        include_conversation: bool,
2606    },
2607    RetrieveContextToggled {
2608        retrieve_context: bool,
2609    },
2610}
2611
2612struct InlineAssistant {
2613    id: usize,
2614    prompt_editor: View<Editor>,
2615    workspace: WeakView<Workspace>,
2616    confirmed: bool,
2617    include_conversation: bool,
2618    measurements: Rc<Cell<BlockMeasurements>>,
2619    prompt_history: VecDeque<String>,
2620    prompt_history_ix: Option<usize>,
2621    pending_prompt: String,
2622    codegen: Model<Codegen>,
2623    _subscriptions: Vec<Subscription>,
2624    retrieve_context: bool,
2625    semantic_index: Option<Model<SemanticIndex>>,
2626    semantic_permissioned: Option<bool>,
2627    project: WeakModel<Project>,
2628    maintain_rate_limit: Option<Task<()>>,
2629}
2630
2631impl EventEmitter<InlineAssistantEvent> for InlineAssistant {}
2632
2633impl Render for InlineAssistant {
2634    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
2635        let measurements = self.measurements.get();
2636        h_stack()
2637            .w_full()
2638            .py_2()
2639            .border_y_1()
2640            .border_color(cx.theme().colors().border)
2641            .on_action(cx.listener(Self::confirm))
2642            .on_action(cx.listener(Self::cancel))
2643            .on_action(cx.listener(Self::toggle_include_conversation))
2644            .on_action(cx.listener(Self::toggle_retrieve_context))
2645            .on_action(cx.listener(Self::move_up))
2646            .on_action(cx.listener(Self::move_down))
2647            .child(
2648                h_stack()
2649                    .justify_center()
2650                    .w(measurements.gutter_width)
2651                    .child(
2652                        IconButton::new("include_conversation", Icon::Ai)
2653                            .on_click(cx.listener(|this, _, cx| {
2654                                this.toggle_include_conversation(&ToggleIncludeConversation, cx)
2655                            }))
2656                            .selected(self.include_conversation)
2657                            .tooltip(|cx| {
2658                                Tooltip::for_action(
2659                                    "Include Conversation",
2660                                    &ToggleIncludeConversation,
2661                                    cx,
2662                                )
2663                            }),
2664                    )
2665                    .children(if SemanticIndex::enabled(cx) {
2666                        Some(
2667                            IconButton::new("retrieve_context", Icon::MagnifyingGlass)
2668                                .on_click(cx.listener(|this, _, cx| {
2669                                    this.toggle_retrieve_context(&ToggleRetrieveContext, cx)
2670                                }))
2671                                .selected(self.retrieve_context)
2672                                .tooltip(|cx| {
2673                                    Tooltip::for_action(
2674                                        "Retrieve Context",
2675                                        &ToggleRetrieveContext,
2676                                        cx,
2677                                    )
2678                                }),
2679                        )
2680                    } else {
2681                        None
2682                    })
2683                    .children(if let Some(error) = self.codegen.read(cx).error() {
2684                        let error_message = SharedString::from(error.to_string());
2685                        Some(
2686                            div()
2687                                .id("error")
2688                                .tooltip(move |cx| Tooltip::text(error_message.clone(), cx))
2689                                .child(IconElement::new(Icon::XCircle).color(Color::Error)),
2690                        )
2691                    } else {
2692                        None
2693                    }),
2694            )
2695            .child(
2696                h_stack()
2697                    .w_full()
2698                    .ml(measurements.anchor_x - measurements.gutter_width)
2699                    .child(self.render_prompt_editor(cx)),
2700            )
2701            .children(if self.retrieve_context {
2702                self.retrieve_context_status(cx)
2703            } else {
2704                None
2705            })
2706    }
2707}
2708
2709impl FocusableView for InlineAssistant {
2710    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
2711        self.prompt_editor.focus_handle(cx)
2712    }
2713}
2714
2715impl InlineAssistant {
2716    fn new(
2717        id: usize,
2718        measurements: Rc<Cell<BlockMeasurements>>,
2719        include_conversation: bool,
2720        prompt_history: VecDeque<String>,
2721        codegen: Model<Codegen>,
2722        workspace: WeakView<Workspace>,
2723        cx: &mut ViewContext<Self>,
2724        retrieve_context: bool,
2725        semantic_index: Option<Model<SemanticIndex>>,
2726        project: Model<Project>,
2727    ) -> Self {
2728        let prompt_editor = cx.new_view(|cx| {
2729            let mut editor = Editor::single_line(cx);
2730            let placeholder = match codegen.read(cx).kind() {
2731                CodegenKind::Transform { .. } => "Enter transformation prompt…",
2732                CodegenKind::Generate { .. } => "Enter generation prompt…",
2733            };
2734            editor.set_placeholder_text(placeholder, cx);
2735            editor
2736        });
2737        cx.focus_view(&prompt_editor);
2738
2739        let mut subscriptions = vec![
2740            cx.observe(&codegen, Self::handle_codegen_changed),
2741            cx.subscribe(&prompt_editor, Self::handle_prompt_editor_events),
2742        ];
2743
2744        if let Some(semantic_index) = semantic_index.clone() {
2745            subscriptions.push(cx.observe(&semantic_index, Self::semantic_index_changed));
2746        }
2747
2748        let assistant = Self {
2749            id,
2750            prompt_editor,
2751            workspace,
2752            confirmed: false,
2753            include_conversation,
2754            measurements,
2755            prompt_history,
2756            prompt_history_ix: None,
2757            pending_prompt: String::new(),
2758            codegen,
2759            _subscriptions: subscriptions,
2760            retrieve_context,
2761            semantic_permissioned: None,
2762            semantic_index,
2763            project: project.downgrade(),
2764            maintain_rate_limit: None,
2765        };
2766
2767        assistant.index_project(cx).log_err();
2768
2769        assistant
2770    }
2771
2772    fn semantic_permissioned(&self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
2773        if let Some(value) = self.semantic_permissioned {
2774            return Task::ready(Ok(value));
2775        }
2776
2777        let Some(project) = self.project.upgrade() else {
2778            return Task::ready(Err(anyhow!("project was dropped")));
2779        };
2780
2781        self.semantic_index
2782            .as_ref()
2783            .map(|semantic| {
2784                semantic.update(cx, |this, cx| this.project_previously_indexed(&project, cx))
2785            })
2786            .unwrap_or(Task::ready(Ok(false)))
2787    }
2788
2789    fn handle_prompt_editor_events(
2790        &mut self,
2791        _: View<Editor>,
2792        event: &EditorEvent,
2793        cx: &mut ViewContext<Self>,
2794    ) {
2795        if let EditorEvent::Edited = event {
2796            self.pending_prompt = self.prompt_editor.read(cx).text(cx);
2797            cx.notify();
2798        }
2799    }
2800
2801    fn semantic_index_changed(
2802        &mut self,
2803        semantic_index: Model<SemanticIndex>,
2804        cx: &mut ViewContext<Self>,
2805    ) {
2806        let Some(project) = self.project.upgrade() else {
2807            return;
2808        };
2809
2810        let status = semantic_index.read(cx).status(&project);
2811        match status {
2812            SemanticIndexStatus::Indexing {
2813                rate_limit_expiry: Some(_),
2814                ..
2815            } => {
2816                if self.maintain_rate_limit.is_none() {
2817                    self.maintain_rate_limit = Some(cx.spawn(|this, mut cx| async move {
2818                        loop {
2819                            cx.background_executor().timer(Duration::from_secs(1)).await;
2820                            this.update(&mut cx, |_, cx| cx.notify()).log_err();
2821                        }
2822                    }));
2823                }
2824                return;
2825            }
2826            _ => {
2827                self.maintain_rate_limit = None;
2828            }
2829        }
2830    }
2831
2832    fn handle_codegen_changed(&mut self, _: Model<Codegen>, cx: &mut ViewContext<Self>) {
2833        let is_read_only = !self.codegen.read(cx).idle();
2834        self.prompt_editor.update(cx, |editor, cx| {
2835            let was_read_only = editor.read_only(cx);
2836            if was_read_only != is_read_only {
2837                if is_read_only {
2838                    editor.set_read_only(true);
2839                } else {
2840                    self.confirmed = false;
2841                    editor.set_read_only(false);
2842                }
2843            }
2844        });
2845        cx.notify();
2846    }
2847
2848    fn cancel(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
2849        cx.emit(InlineAssistantEvent::Canceled);
2850    }
2851
2852    fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
2853        if self.confirmed {
2854            cx.emit(InlineAssistantEvent::Dismissed);
2855        } else {
2856            report_assistant_event(self.workspace.clone(), None, AssistantKind::Inline, cx);
2857
2858            let prompt = self.prompt_editor.read(cx).text(cx);
2859            self.prompt_editor
2860                .update(cx, |editor, _cx| editor.set_read_only(true));
2861            cx.emit(InlineAssistantEvent::Confirmed {
2862                prompt,
2863                include_conversation: self.include_conversation,
2864                retrieve_context: self.retrieve_context,
2865            });
2866            self.confirmed = true;
2867            cx.notify();
2868        }
2869    }
2870
2871    fn toggle_retrieve_context(&mut self, _: &ToggleRetrieveContext, cx: &mut ViewContext<Self>) {
2872        let semantic_permissioned = self.semantic_permissioned(cx);
2873
2874        let Some(project) = self.project.upgrade() else {
2875            return;
2876        };
2877
2878        let project_name = project
2879            .read(cx)
2880            .worktree_root_names(cx)
2881            .collect::<Vec<&str>>()
2882            .join("/");
2883        let is_plural = project_name.chars().filter(|letter| *letter == '/').count() > 0;
2884        let prompt_text = format!("Would you like to index the '{}' project{} for context retrieval? This requires sending code to the OpenAI API", project_name,
2885            if is_plural {
2886                "s"
2887            } else {""});
2888
2889        cx.spawn(|this, mut cx| async move {
2890            // If Necessary prompt user
2891            if !semantic_permissioned.await.unwrap_or(false) {
2892                let answer = this.update(&mut cx, |_, cx| {
2893                    cx.prompt(
2894                        PromptLevel::Info,
2895                        prompt_text.as_str(),
2896                        &["Continue", "Cancel"],
2897                    )
2898                })?;
2899
2900                if answer.await? == 0 {
2901                    this.update(&mut cx, |this, _| {
2902                        this.semantic_permissioned = Some(true);
2903                    })?;
2904                } else {
2905                    return anyhow::Ok(());
2906                }
2907            }
2908
2909            // If permissioned, update context appropriately
2910            this.update(&mut cx, |this, cx| {
2911                this.retrieve_context = !this.retrieve_context;
2912
2913                cx.emit(InlineAssistantEvent::RetrieveContextToggled {
2914                    retrieve_context: this.retrieve_context,
2915                });
2916
2917                if this.retrieve_context {
2918                    this.index_project(cx).log_err();
2919                }
2920
2921                cx.notify();
2922            })?;
2923
2924            anyhow::Ok(())
2925        })
2926        .detach_and_log_err(cx);
2927    }
2928
2929    fn index_project(&self, cx: &mut ViewContext<Self>) -> anyhow::Result<()> {
2930        let Some(project) = self.project.upgrade() else {
2931            return Err(anyhow!("project was dropped!"));
2932        };
2933
2934        let semantic_permissioned = self.semantic_permissioned(cx);
2935        if let Some(semantic_index) = SemanticIndex::global(cx) {
2936            cx.spawn(|_, mut cx| async move {
2937                // This has to be updated to accomodate for semantic_permissions
2938                if semantic_permissioned.await.unwrap_or(false) {
2939                    semantic_index
2940                        .update(&mut cx, |index, cx| index.index_project(project, cx))?
2941                        .await
2942                } else {
2943                    Err(anyhow!("project is not permissioned for semantic indexing"))
2944                }
2945            })
2946            .detach_and_log_err(cx);
2947        }
2948
2949        anyhow::Ok(())
2950    }
2951
2952    fn retrieve_context_status(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
2953        let Some(project) = self.project.upgrade() else {
2954            return None;
2955        };
2956
2957        let semantic_index = SemanticIndex::global(cx)?;
2958        let status = semantic_index.update(cx, |index, _| index.status(&project));
2959        match status {
2960            SemanticIndexStatus::NotAuthenticated {} => Some(
2961                div()
2962                    .id("error")
2963                    .tooltip(|cx| Tooltip::text("Not Authenticated. Please ensure you have a valid 'OPENAI_API_KEY' in your environment variables.", cx))
2964                    .child(IconElement::new(Icon::XCircle))
2965                    .into_any_element()
2966            ),
2967
2968            SemanticIndexStatus::NotIndexed {} => Some(
2969                div()
2970                    .id("error")
2971                    .tooltip(|cx| Tooltip::text("Not Indexed", cx))
2972                    .child(IconElement::new(Icon::XCircle))
2973                    .into_any_element()
2974            ),
2975
2976            SemanticIndexStatus::Indexing {
2977                remaining_files,
2978                rate_limit_expiry,
2979            } => {
2980                let mut status_text = if remaining_files == 0 {
2981                    "Indexing...".to_string()
2982                } else {
2983                    format!("Remaining files to index: {remaining_files}")
2984                };
2985
2986                if let Some(rate_limit_expiry) = rate_limit_expiry {
2987                    let remaining_seconds = rate_limit_expiry.duration_since(Instant::now());
2988                    if remaining_seconds > Duration::from_secs(0) && remaining_files > 0 {
2989                        write!(
2990                            status_text,
2991                            " (rate limit expires in {}s)",
2992                            remaining_seconds.as_secs()
2993                        )
2994                        .unwrap();
2995                    }
2996                }
2997
2998                let status_text = SharedString::from(status_text);
2999                Some(
3000                    div()
3001                        .id("update")
3002                        .tooltip(move |cx| Tooltip::text(status_text.clone(), cx))
3003                        .child(IconElement::new(Icon::Update).color(Color::Info))
3004                        .into_any_element()
3005                )
3006            }
3007
3008            SemanticIndexStatus::Indexed {} => Some(
3009                div()
3010                    .id("check")
3011                    .tooltip(|cx| Tooltip::text("Index up to date", cx))
3012                    .child(IconElement::new(Icon::Check).color(Color::Success))
3013                    .into_any_element()
3014            ),
3015        }
3016    }
3017
3018    fn toggle_include_conversation(
3019        &mut self,
3020        _: &ToggleIncludeConversation,
3021        cx: &mut ViewContext<Self>,
3022    ) {
3023        self.include_conversation = !self.include_conversation;
3024        cx.emit(InlineAssistantEvent::IncludeConversationToggled {
3025            include_conversation: self.include_conversation,
3026        });
3027        cx.notify();
3028    }
3029
3030    fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
3031        if let Some(ix) = self.prompt_history_ix {
3032            if ix > 0 {
3033                self.prompt_history_ix = Some(ix - 1);
3034                let prompt = self.prompt_history[ix - 1].clone();
3035                self.set_prompt(&prompt, cx);
3036            }
3037        } else if !self.prompt_history.is_empty() {
3038            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
3039            let prompt = self.prompt_history[self.prompt_history.len() - 1].clone();
3040            self.set_prompt(&prompt, cx);
3041        }
3042    }
3043
3044    fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
3045        if let Some(ix) = self.prompt_history_ix {
3046            if ix < self.prompt_history.len() - 1 {
3047                self.prompt_history_ix = Some(ix + 1);
3048                let prompt = self.prompt_history[ix + 1].clone();
3049                self.set_prompt(&prompt, cx);
3050            } else {
3051                self.prompt_history_ix = None;
3052                let pending_prompt = self.pending_prompt.clone();
3053                self.set_prompt(&pending_prompt, cx);
3054            }
3055        }
3056    }
3057
3058    fn set_prompt(&mut self, prompt: &str, cx: &mut ViewContext<Self>) {
3059        self.prompt_editor.update(cx, |editor, cx| {
3060            editor.buffer().update(cx, |buffer, cx| {
3061                let len = buffer.len(cx);
3062                buffer.edit([(0..len, prompt)], None, cx);
3063            });
3064        });
3065    }
3066
3067    fn render_prompt_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3068        let settings = ThemeSettings::get_global(cx);
3069        let text_style = TextStyle {
3070            color: if self.prompt_editor.read(cx).read_only(cx) {
3071                cx.theme().colors().text_disabled
3072            } else {
3073                cx.theme().colors().text
3074            },
3075            font_family: settings.ui_font.family.clone(),
3076            font_features: settings.ui_font.features,
3077            font_size: rems(0.875).into(),
3078            font_weight: FontWeight::NORMAL,
3079            font_style: FontStyle::Normal,
3080            line_height: relative(1.3).into(),
3081            background_color: None,
3082            underline: None,
3083            white_space: WhiteSpace::Normal,
3084        };
3085        EditorElement::new(
3086            &self.prompt_editor,
3087            EditorStyle {
3088                background: cx.theme().colors().editor_background,
3089                local_player: cx.theme().players().local(),
3090                text: text_style,
3091                ..Default::default()
3092            },
3093        )
3094    }
3095}
3096
3097// This wouldn't need to exist if we could pass parameters when rendering child views.
3098#[derive(Copy, Clone, Default)]
3099struct BlockMeasurements {
3100    anchor_x: Pixels,
3101    gutter_width: Pixels,
3102}
3103
3104struct PendingInlineAssist {
3105    editor: WeakView<Editor>,
3106    inline_assistant: Option<(BlockId, View<InlineAssistant>)>,
3107    codegen: Model<Codegen>,
3108    _subscriptions: Vec<Subscription>,
3109    project: WeakModel<Project>,
3110}
3111
3112fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3113    ranges.sort_unstable_by(|a, b| {
3114        a.start
3115            .cmp(&b.start, buffer)
3116            .then_with(|| b.end.cmp(&a.end, buffer))
3117    });
3118
3119    let mut ix = 0;
3120    while ix + 1 < ranges.len() {
3121        let b = ranges[ix + 1].clone();
3122        let a = &mut ranges[ix];
3123        if a.end.cmp(&b.start, buffer).is_gt() {
3124            if a.end.cmp(&b.end, buffer).is_lt() {
3125                a.end = b.end;
3126            }
3127            ranges.remove(ix + 1);
3128        } else {
3129            ix += 1;
3130        }
3131    }
3132}
3133
3134#[cfg(test)]
3135mod tests {
3136    use super::*;
3137    use crate::MessageId;
3138    use ai::test::FakeCompletionProvider;
3139    use gpui::AppContext;
3140
3141    #[gpui::test]
3142    fn test_inserting_and_removing_messages(cx: &mut AppContext) {
3143        let settings_store = SettingsStore::test(cx);
3144        cx.set_global(settings_store);
3145        init(cx);
3146        let registry = Arc::new(LanguageRegistry::test());
3147
3148        let completion_provider = Arc::new(FakeCompletionProvider::new());
3149        let conversation = cx.new_model(|cx| Conversation::new(registry, cx, completion_provider));
3150        let buffer = conversation.read(cx).buffer.clone();
3151
3152        let message_1 = conversation.read(cx).message_anchors[0].clone();
3153        assert_eq!(
3154            messages(&conversation, cx),
3155            vec![(message_1.id, Role::User, 0..0)]
3156        );
3157
3158        let message_2 = conversation.update(cx, |conversation, cx| {
3159            conversation
3160                .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx)
3161                .unwrap()
3162        });
3163        assert_eq!(
3164            messages(&conversation, cx),
3165            vec![
3166                (message_1.id, Role::User, 0..1),
3167                (message_2.id, Role::Assistant, 1..1)
3168            ]
3169        );
3170
3171        buffer.update(cx, |buffer, cx| {
3172            buffer.edit([(0..0, "1"), (1..1, "2")], None, cx)
3173        });
3174        assert_eq!(
3175            messages(&conversation, cx),
3176            vec![
3177                (message_1.id, Role::User, 0..2),
3178                (message_2.id, Role::Assistant, 2..3)
3179            ]
3180        );
3181
3182        let message_3 = conversation.update(cx, |conversation, cx| {
3183            conversation
3184                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3185                .unwrap()
3186        });
3187        assert_eq!(
3188            messages(&conversation, cx),
3189            vec![
3190                (message_1.id, Role::User, 0..2),
3191                (message_2.id, Role::Assistant, 2..4),
3192                (message_3.id, Role::User, 4..4)
3193            ]
3194        );
3195
3196        let message_4 = conversation.update(cx, |conversation, cx| {
3197            conversation
3198                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3199                .unwrap()
3200        });
3201        assert_eq!(
3202            messages(&conversation, cx),
3203            vec![
3204                (message_1.id, Role::User, 0..2),
3205                (message_2.id, Role::Assistant, 2..4),
3206                (message_4.id, Role::User, 4..5),
3207                (message_3.id, Role::User, 5..5),
3208            ]
3209        );
3210
3211        buffer.update(cx, |buffer, cx| {
3212            buffer.edit([(4..4, "C"), (5..5, "D")], None, cx)
3213        });
3214        assert_eq!(
3215            messages(&conversation, cx),
3216            vec![
3217                (message_1.id, Role::User, 0..2),
3218                (message_2.id, Role::Assistant, 2..4),
3219                (message_4.id, Role::User, 4..6),
3220                (message_3.id, Role::User, 6..7),
3221            ]
3222        );
3223
3224        // Deleting across message boundaries merges the messages.
3225        buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx));
3226        assert_eq!(
3227            messages(&conversation, cx),
3228            vec![
3229                (message_1.id, Role::User, 0..3),
3230                (message_3.id, Role::User, 3..4),
3231            ]
3232        );
3233
3234        // Undoing the deletion should also undo the merge.
3235        buffer.update(cx, |buffer, cx| buffer.undo(cx));
3236        assert_eq!(
3237            messages(&conversation, cx),
3238            vec![
3239                (message_1.id, Role::User, 0..2),
3240                (message_2.id, Role::Assistant, 2..4),
3241                (message_4.id, Role::User, 4..6),
3242                (message_3.id, Role::User, 6..7),
3243            ]
3244        );
3245
3246        // Redoing the deletion should also redo the merge.
3247        buffer.update(cx, |buffer, cx| buffer.redo(cx));
3248        assert_eq!(
3249            messages(&conversation, cx),
3250            vec![
3251                (message_1.id, Role::User, 0..3),
3252                (message_3.id, Role::User, 3..4),
3253            ]
3254        );
3255
3256        // Ensure we can still insert after a merged message.
3257        let message_5 = conversation.update(cx, |conversation, cx| {
3258            conversation
3259                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3260                .unwrap()
3261        });
3262        assert_eq!(
3263            messages(&conversation, cx),
3264            vec![
3265                (message_1.id, Role::User, 0..3),
3266                (message_5.id, Role::System, 3..4),
3267                (message_3.id, Role::User, 4..5)
3268            ]
3269        );
3270    }
3271
3272    #[gpui::test]
3273    fn test_message_splitting(cx: &mut AppContext) {
3274        let settings_store = SettingsStore::test(cx);
3275        cx.set_global(settings_store);
3276        init(cx);
3277        let registry = Arc::new(LanguageRegistry::test());
3278        let completion_provider = Arc::new(FakeCompletionProvider::new());
3279
3280        let conversation = cx.new_model(|cx| Conversation::new(registry, cx, completion_provider));
3281        let buffer = conversation.read(cx).buffer.clone();
3282
3283        let message_1 = conversation.read(cx).message_anchors[0].clone();
3284        assert_eq!(
3285            messages(&conversation, cx),
3286            vec![(message_1.id, Role::User, 0..0)]
3287        );
3288
3289        buffer.update(cx, |buffer, cx| {
3290            buffer.edit([(0..0, "aaa\nbbb\nccc\nddd\n")], None, cx)
3291        });
3292
3293        let (_, message_2) =
3294            conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx));
3295        let message_2 = message_2.unwrap();
3296
3297        // We recycle newlines in the middle of a split message
3298        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n");
3299        assert_eq!(
3300            messages(&conversation, cx),
3301            vec![
3302                (message_1.id, Role::User, 0..4),
3303                (message_2.id, Role::User, 4..16),
3304            ]
3305        );
3306
3307        let (_, message_3) =
3308            conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx));
3309        let message_3 = message_3.unwrap();
3310
3311        // We don't recycle newlines at the end of a split message
3312        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
3313        assert_eq!(
3314            messages(&conversation, cx),
3315            vec![
3316                (message_1.id, Role::User, 0..4),
3317                (message_3.id, Role::User, 4..5),
3318                (message_2.id, Role::User, 5..17),
3319            ]
3320        );
3321
3322        let (_, message_4) =
3323            conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx));
3324        let message_4 = message_4.unwrap();
3325        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
3326        assert_eq!(
3327            messages(&conversation, cx),
3328            vec![
3329                (message_1.id, Role::User, 0..4),
3330                (message_3.id, Role::User, 4..5),
3331                (message_2.id, Role::User, 5..9),
3332                (message_4.id, Role::User, 9..17),
3333            ]
3334        );
3335
3336        let (_, message_5) =
3337            conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx));
3338        let message_5 = message_5.unwrap();
3339        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n");
3340        assert_eq!(
3341            messages(&conversation, cx),
3342            vec![
3343                (message_1.id, Role::User, 0..4),
3344                (message_3.id, Role::User, 4..5),
3345                (message_2.id, Role::User, 5..9),
3346                (message_4.id, Role::User, 9..10),
3347                (message_5.id, Role::User, 10..18),
3348            ]
3349        );
3350
3351        let (message_6, message_7) = conversation.update(cx, |conversation, cx| {
3352            conversation.split_message(14..16, cx)
3353        });
3354        let message_6 = message_6.unwrap();
3355        let message_7 = message_7.unwrap();
3356        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n");
3357        assert_eq!(
3358            messages(&conversation, cx),
3359            vec![
3360                (message_1.id, Role::User, 0..4),
3361                (message_3.id, Role::User, 4..5),
3362                (message_2.id, Role::User, 5..9),
3363                (message_4.id, Role::User, 9..10),
3364                (message_5.id, Role::User, 10..14),
3365                (message_6.id, Role::User, 14..17),
3366                (message_7.id, Role::User, 17..19),
3367            ]
3368        );
3369    }
3370
3371    #[gpui::test]
3372    fn test_messages_for_offsets(cx: &mut AppContext) {
3373        let settings_store = SettingsStore::test(cx);
3374        cx.set_global(settings_store);
3375        init(cx);
3376        let registry = Arc::new(LanguageRegistry::test());
3377        let completion_provider = Arc::new(FakeCompletionProvider::new());
3378        let conversation = cx.new_model(|cx| Conversation::new(registry, cx, completion_provider));
3379        let buffer = conversation.read(cx).buffer.clone();
3380
3381        let message_1 = conversation.read(cx).message_anchors[0].clone();
3382        assert_eq!(
3383            messages(&conversation, cx),
3384            vec![(message_1.id, Role::User, 0..0)]
3385        );
3386
3387        buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx));
3388        let message_2 = conversation
3389            .update(cx, |conversation, cx| {
3390                conversation.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx)
3391            })
3392            .unwrap();
3393        buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx));
3394
3395        let message_3 = conversation
3396            .update(cx, |conversation, cx| {
3397                conversation.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3398            })
3399            .unwrap();
3400        buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx));
3401
3402        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc");
3403        assert_eq!(
3404            messages(&conversation, cx),
3405            vec![
3406                (message_1.id, Role::User, 0..4),
3407                (message_2.id, Role::User, 4..8),
3408                (message_3.id, Role::User, 8..11)
3409            ]
3410        );
3411
3412        assert_eq!(
3413            message_ids_for_offsets(&conversation, &[0, 4, 9], cx),
3414            [message_1.id, message_2.id, message_3.id]
3415        );
3416        assert_eq!(
3417            message_ids_for_offsets(&conversation, &[0, 1, 11], cx),
3418            [message_1.id, message_3.id]
3419        );
3420
3421        let message_4 = conversation
3422            .update(cx, |conversation, cx| {
3423                conversation.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx)
3424            })
3425            .unwrap();
3426        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n");
3427        assert_eq!(
3428            messages(&conversation, cx),
3429            vec![
3430                (message_1.id, Role::User, 0..4),
3431                (message_2.id, Role::User, 4..8),
3432                (message_3.id, Role::User, 8..12),
3433                (message_4.id, Role::User, 12..12)
3434            ]
3435        );
3436        assert_eq!(
3437            message_ids_for_offsets(&conversation, &[0, 4, 8, 12], cx),
3438            [message_1.id, message_2.id, message_3.id, message_4.id]
3439        );
3440
3441        fn message_ids_for_offsets(
3442            conversation: &Model<Conversation>,
3443            offsets: &[usize],
3444            cx: &AppContext,
3445        ) -> Vec<MessageId> {
3446            conversation
3447                .read(cx)
3448                .messages_for_offsets(offsets.iter().copied(), cx)
3449                .into_iter()
3450                .map(|message| message.id)
3451                .collect()
3452        }
3453    }
3454
3455    #[gpui::test]
3456    fn test_serialization(cx: &mut AppContext) {
3457        let settings_store = SettingsStore::test(cx);
3458        cx.set_global(settings_store);
3459        init(cx);
3460        let registry = Arc::new(LanguageRegistry::test());
3461        let completion_provider = Arc::new(FakeCompletionProvider::new());
3462        let conversation =
3463            cx.new_model(|cx| Conversation::new(registry.clone(), cx, completion_provider));
3464        let buffer = conversation.read(cx).buffer.clone();
3465        let message_0 = conversation.read(cx).message_anchors[0].id;
3466        let message_1 = conversation.update(cx, |conversation, cx| {
3467            conversation
3468                .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx)
3469                .unwrap()
3470        });
3471        let message_2 = conversation.update(cx, |conversation, cx| {
3472            conversation
3473                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3474                .unwrap()
3475        });
3476        buffer.update(cx, |buffer, cx| {
3477            buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx);
3478            buffer.finalize_last_transaction();
3479        });
3480        let _message_3 = conversation.update(cx, |conversation, cx| {
3481            conversation
3482                .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx)
3483                .unwrap()
3484        });
3485        buffer.update(cx, |buffer, cx| buffer.undo(cx));
3486        assert_eq!(buffer.read(cx).text(), "a\nb\nc\n");
3487        assert_eq!(
3488            messages(&conversation, cx),
3489            [
3490                (message_0, Role::User, 0..2),
3491                (message_1.id, Role::Assistant, 2..6),
3492                (message_2.id, Role::System, 6..6),
3493            ]
3494        );
3495
3496        let deserialized_conversation = cx.new_model(|cx| {
3497            Conversation::deserialize(
3498                conversation.read(cx).serialize(cx),
3499                Default::default(),
3500                registry.clone(),
3501                cx,
3502            )
3503        });
3504        let deserialized_buffer = deserialized_conversation.read(cx).buffer.clone();
3505        assert_eq!(deserialized_buffer.read(cx).text(), "a\nb\nc\n");
3506        assert_eq!(
3507            messages(&deserialized_conversation, cx),
3508            [
3509                (message_0, Role::User, 0..2),
3510                (message_1.id, Role::Assistant, 2..6),
3511                (message_2.id, Role::System, 6..6),
3512            ]
3513        );
3514    }
3515
3516    fn messages(
3517        conversation: &Model<Conversation>,
3518        cx: &AppContext,
3519    ) -> Vec<(MessageId, Role, Range<usize>)> {
3520        conversation
3521            .read(cx)
3522            .messages(cx)
3523            .map(|message| (message.id, message.role, message.offset_range))
3524            .collect()
3525    }
3526}
3527
3528fn report_assistant_event(
3529    workspace: WeakView<Workspace>,
3530    conversation_id: Option<String>,
3531    assistant_kind: AssistantKind,
3532    cx: &AppContext,
3533) {
3534    let Some(workspace) = workspace.upgrade() else {
3535        return;
3536    };
3537
3538    let client = workspace.read(cx).project().read(cx).client();
3539    let telemetry = client.telemetry();
3540
3541    let model = AssistantSettings::get_global(cx)
3542        .default_open_ai_model
3543        .clone();
3544
3545    telemetry.report_assistant_event(conversation_id, assistant_kind, model.full_name(), cx)
3546}