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