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