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