assistant_panel.rs

   1use crate::{
   2    assistant_settings::{AssistantDockPosition, AssistantSettings, OpenAIModel},
   3    codegen::{self, Codegen, CodegenKind},
   4    prompts::generate_content_prompt,
   5    Assist, CycleMessageRole, InlineAssist, MessageId, MessageMetadata, MessageStatus,
   6    NewConversation, QuoteSelection, ResetKey, Role, SavedConversation, SavedConversationMetadata,
   7    SavedMessage, Split, ToggleFocus, ToggleIncludeConversation, ToggleRetrieveContext,
   8};
   9
  10use ai::{
  11    auth::ProviderCredential,
  12    completion::{CompletionProvider, CompletionRequest},
  13    providers::open_ai::{OpenAICompletionProvider, OpenAIRequest, RequestMessage},
  14};
  15
  16use ai::prompts::repository_context::PromptCodeSnippet;
  17use anyhow::{anyhow, Result};
  18use chrono::{DateTime, Local};
  19use client::{telemetry::AssistantKind, TelemetrySettings};
  20use collections::{hash_map, HashMap, HashSet, VecDeque};
  21use editor::{
  22    display_map::{
  23        BlockContext, BlockDisposition, BlockId, BlockProperties, BlockStyle, ToDisplayPoint,
  24    },
  25    scroll::autoscroll::{Autoscroll, AutoscrollStrategy},
  26    Anchor, Editor, EditorElement, EditorEvent, EditorStyle, MoveDown, MoveUp, MultiBufferSnapshot,
  27    ToOffset, ToPoint,
  28};
  29use fs::Fs;
  30use futures::StreamExt;
  31use gpui::{
  32    div, point, relative, rems, uniform_list, Action, AnyElement, AppContext, AsyncWindowContext,
  33    ClipboardItem, Context, Div, EventEmitter, FocusHandle, Focusable, FocusableView, FontStyle,
  34    FontWeight, HighlightStyle, InteractiveElement, IntoElement, Model, ModelContext,
  35    ParentElement, Pixels, PromptLevel, Render, SharedString, StatefulInteractiveElement, Styled,
  36    Subscription, Task, TextStyle, UniformListScrollHandle, View, ViewContext, VisualContext,
  37    WeakModel, WeakView, WhiteSpace, WindowContext,
  38};
  39use language::{language_settings::SoftWrap, Buffer, LanguageRegistry, ToOffset as _};
  40use project::Project;
  41use search::BufferSearchBar;
  42use semantic_index::{SemanticIndex, SemanticIndexStatus};
  43use settings::{Settings, SettingsStore};
  44use std::{
  45    cell::Cell,
  46    cmp,
  47    fmt::Write,
  48    iter,
  49    ops::Range,
  50    path::{Path, PathBuf},
  51    rc::Rc,
  52    sync::Arc,
  53    time::{Duration, Instant},
  54};
  55use theme::ThemeSettings;
  56use ui::{
  57    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                            uniform_list(
1188                                cx.view().clone(),
1189                                "saved_conversations",
1190                                self.saved_conversations.len(),
1191                                |this, range, cx| {
1192                                    range
1193                                        .map(|ix| this.render_saved_conversation(ix, cx))
1194                                        .collect()
1195                                },
1196                            )
1197                            .track_scroll(self.saved_conversations_scroll_handle.clone())
1198                            .into_any_element()
1199                        }),
1200                )
1201        }
1202    }
1203}
1204
1205impl Panel for AssistantPanel {
1206    fn persistent_name() -> &'static str {
1207        "AssistantPanel"
1208    }
1209
1210    fn position(&self, cx: &WindowContext) -> DockPosition {
1211        match AssistantSettings::get_global(cx).dock {
1212            AssistantDockPosition::Left => DockPosition::Left,
1213            AssistantDockPosition::Bottom => DockPosition::Bottom,
1214            AssistantDockPosition::Right => DockPosition::Right,
1215        }
1216    }
1217
1218    fn position_is_valid(&self, _: DockPosition) -> bool {
1219        true
1220    }
1221
1222    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1223        settings::update_settings_file::<AssistantSettings>(self.fs.clone(), cx, move |settings| {
1224            let dock = match position {
1225                DockPosition::Left => AssistantDockPosition::Left,
1226                DockPosition::Bottom => AssistantDockPosition::Bottom,
1227                DockPosition::Right => AssistantDockPosition::Right,
1228            };
1229            settings.dock = Some(dock);
1230        });
1231    }
1232
1233    fn size(&self, cx: &WindowContext) -> f32 {
1234        let settings = AssistantSettings::get_global(cx);
1235        match self.position(cx) {
1236            DockPosition::Left | DockPosition::Right => {
1237                self.width.unwrap_or_else(|| settings.default_width)
1238            }
1239            DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
1240        }
1241    }
1242
1243    fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
1244        match self.position(cx) {
1245            DockPosition::Left | DockPosition::Right => self.width = size,
1246            DockPosition::Bottom => self.height = size,
1247        }
1248        cx.notify();
1249    }
1250
1251    fn is_zoomed(&self, _: &WindowContext) -> bool {
1252        self.zoomed
1253    }
1254
1255    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1256        self.zoomed = zoomed;
1257        cx.notify();
1258    }
1259
1260    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1261        if active {
1262            self.load_credentials(cx);
1263
1264            if self.editors.is_empty() {
1265                self.new_conversation(cx);
1266            }
1267        }
1268    }
1269
1270    fn icon(&self, _cx: &WindowContext) -> Option<Icon> {
1271        Some(Icon::Ai)
1272    }
1273
1274    fn toggle_action(&self) -> Box<dyn Action> {
1275        Box::new(ToggleFocus)
1276    }
1277}
1278
1279impl EventEmitter<PanelEvent> for AssistantPanel {}
1280
1281impl FocusableView for AssistantPanel {
1282    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1283        self.focus_handle.clone()
1284    }
1285}
1286
1287enum ConversationEvent {
1288    MessagesEdited,
1289    SummaryChanged,
1290    StreamedCompletion,
1291}
1292
1293#[derive(Default)]
1294struct Summary {
1295    text: String,
1296    done: bool,
1297}
1298
1299struct Conversation {
1300    id: Option<String>,
1301    buffer: Model<Buffer>,
1302    message_anchors: Vec<MessageAnchor>,
1303    messages_metadata: HashMap<MessageId, MessageMetadata>,
1304    next_message_id: MessageId,
1305    summary: Option<Summary>,
1306    pending_summary: Task<Option<()>>,
1307    completion_count: usize,
1308    pending_completions: Vec<PendingCompletion>,
1309    model: OpenAIModel,
1310    token_count: Option<usize>,
1311    max_token_count: usize,
1312    pending_token_count: Task<Option<()>>,
1313    pending_save: Task<Result<()>>,
1314    path: Option<PathBuf>,
1315    _subscriptions: Vec<Subscription>,
1316    completion_provider: Arc<dyn CompletionProvider>,
1317}
1318
1319impl EventEmitter<ConversationEvent> for Conversation {}
1320
1321impl Conversation {
1322    fn new(
1323        language_registry: Arc<LanguageRegistry>,
1324        cx: &mut ModelContext<Self>,
1325        completion_provider: Arc<dyn CompletionProvider>,
1326    ) -> Self {
1327        let markdown = language_registry.language_for_name("Markdown");
1328        let buffer = cx.build_model(|cx| {
1329            let mut buffer = Buffer::new(0, cx.entity_id().as_u64(), "");
1330            buffer.set_language_registry(language_registry);
1331            cx.spawn(|buffer, mut cx| async move {
1332                let markdown = markdown.await?;
1333                buffer.update(&mut cx, |buffer: &mut Buffer, cx| {
1334                    buffer.set_language(Some(markdown), cx)
1335                })?;
1336                anyhow::Ok(())
1337            })
1338            .detach_and_log_err(cx);
1339            buffer
1340        });
1341
1342        let settings = AssistantSettings::get_global(cx);
1343        let model = settings.default_open_ai_model.clone();
1344
1345        let mut this = Self {
1346            id: Some(Uuid::new_v4().to_string()),
1347            message_anchors: Default::default(),
1348            messages_metadata: Default::default(),
1349            next_message_id: Default::default(),
1350            summary: None,
1351            pending_summary: Task::ready(None),
1352            completion_count: Default::default(),
1353            pending_completions: Default::default(),
1354            token_count: None,
1355            max_token_count: tiktoken_rs::model::get_context_size(&model.full_name()),
1356            pending_token_count: Task::ready(None),
1357            model: model.clone(),
1358            _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
1359            pending_save: Task::ready(Ok(())),
1360            path: None,
1361            buffer,
1362            completion_provider,
1363        };
1364        let message = MessageAnchor {
1365            id: MessageId(post_inc(&mut this.next_message_id.0)),
1366            start: language::Anchor::MIN,
1367        };
1368        this.message_anchors.push(message.clone());
1369        this.messages_metadata.insert(
1370            message.id,
1371            MessageMetadata {
1372                role: Role::User,
1373                sent_at: Local::now(),
1374                status: MessageStatus::Done,
1375            },
1376        );
1377
1378        this.count_remaining_tokens(cx);
1379        this
1380    }
1381
1382    fn serialize(&self, cx: &AppContext) -> SavedConversation {
1383        SavedConversation {
1384            id: self.id.clone(),
1385            zed: "conversation".into(),
1386            version: SavedConversation::VERSION.into(),
1387            text: self.buffer.read(cx).text(),
1388            message_metadata: self.messages_metadata.clone(),
1389            messages: self
1390                .messages(cx)
1391                .map(|message| SavedMessage {
1392                    id: message.id,
1393                    start: message.offset_range.start,
1394                })
1395                .collect(),
1396            summary: self
1397                .summary
1398                .as_ref()
1399                .map(|summary| summary.text.clone())
1400                .unwrap_or_default(),
1401            model: self.model.clone(),
1402        }
1403    }
1404
1405    fn deserialize(
1406        saved_conversation: SavedConversation,
1407        path: PathBuf,
1408        language_registry: Arc<LanguageRegistry>,
1409        cx: &mut ModelContext<Self>,
1410    ) -> Self {
1411        let id = match saved_conversation.id {
1412            Some(id) => Some(id),
1413            None => Some(Uuid::new_v4().to_string()),
1414        };
1415        let model = saved_conversation.model;
1416        let completion_provider: Arc<dyn CompletionProvider> = Arc::new(
1417            OpenAICompletionProvider::new(model.full_name(), cx.background_executor().clone()),
1418        );
1419        completion_provider.retrieve_credentials(cx);
1420        let markdown = language_registry.language_for_name("Markdown");
1421        let mut message_anchors = Vec::new();
1422        let mut next_message_id = MessageId(0);
1423        let buffer = cx.build_model(|cx| {
1424            let mut buffer = Buffer::new(0, cx.entity_id().as_u64(), saved_conversation.text);
1425            for message in saved_conversation.messages {
1426                message_anchors.push(MessageAnchor {
1427                    id: message.id,
1428                    start: buffer.anchor_before(message.start),
1429                });
1430                next_message_id = cmp::max(next_message_id, MessageId(message.id.0 + 1));
1431            }
1432            buffer.set_language_registry(language_registry);
1433            cx.spawn(|buffer, mut cx| async move {
1434                let markdown = markdown.await?;
1435                buffer.update(&mut cx, |buffer: &mut Buffer, cx| {
1436                    buffer.set_language(Some(markdown), cx)
1437                })?;
1438                anyhow::Ok(())
1439            })
1440            .detach_and_log_err(cx);
1441            buffer
1442        });
1443
1444        let mut this = Self {
1445            id,
1446            message_anchors,
1447            messages_metadata: saved_conversation.message_metadata,
1448            next_message_id,
1449            summary: Some(Summary {
1450                text: saved_conversation.summary,
1451                done: true,
1452            }),
1453            pending_summary: Task::ready(None),
1454            completion_count: Default::default(),
1455            pending_completions: Default::default(),
1456            token_count: None,
1457            max_token_count: tiktoken_rs::model::get_context_size(&model.full_name()),
1458            pending_token_count: Task::ready(None),
1459            model,
1460            _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
1461            pending_save: Task::ready(Ok(())),
1462            path: Some(path),
1463            buffer,
1464            completion_provider,
1465        };
1466        this.count_remaining_tokens(cx);
1467        this
1468    }
1469
1470    fn handle_buffer_event(
1471        &mut self,
1472        _: Model<Buffer>,
1473        event: &language::Event,
1474        cx: &mut ModelContext<Self>,
1475    ) {
1476        match event {
1477            language::Event::Edited => {
1478                self.count_remaining_tokens(cx);
1479                cx.emit(ConversationEvent::MessagesEdited);
1480            }
1481            _ => {}
1482        }
1483    }
1484
1485    fn count_remaining_tokens(&mut self, cx: &mut ModelContext<Self>) {
1486        let messages = self
1487            .messages(cx)
1488            .into_iter()
1489            .filter_map(|message| {
1490                Some(tiktoken_rs::ChatCompletionRequestMessage {
1491                    role: match message.role {
1492                        Role::User => "user".into(),
1493                        Role::Assistant => "assistant".into(),
1494                        Role::System => "system".into(),
1495                    },
1496                    content: Some(
1497                        self.buffer
1498                            .read(cx)
1499                            .text_for_range(message.offset_range)
1500                            .collect(),
1501                    ),
1502                    name: None,
1503                    function_call: None,
1504                })
1505            })
1506            .collect::<Vec<_>>();
1507        let model = self.model.clone();
1508        self.pending_token_count = cx.spawn(|this, mut cx| {
1509            async move {
1510                cx.background_executor()
1511                    .timer(Duration::from_millis(200))
1512                    .await;
1513                let token_count = cx
1514                    .background_executor()
1515                    .spawn(async move {
1516                        tiktoken_rs::num_tokens_from_messages(&model.full_name(), &messages)
1517                    })
1518                    .await?;
1519
1520                this.update(&mut cx, |this, cx| {
1521                    this.max_token_count =
1522                        tiktoken_rs::model::get_context_size(&this.model.full_name());
1523                    this.token_count = Some(token_count);
1524                    cx.notify()
1525                })?;
1526                anyhow::Ok(())
1527            }
1528            .log_err()
1529        });
1530    }
1531
1532    fn remaining_tokens(&self) -> Option<isize> {
1533        Some(self.max_token_count as isize - self.token_count? as isize)
1534    }
1535
1536    fn set_model(&mut self, model: OpenAIModel, cx: &mut ModelContext<Self>) {
1537        self.model = model;
1538        self.count_remaining_tokens(cx);
1539        cx.notify();
1540    }
1541
1542    fn assist(
1543        &mut self,
1544        selected_messages: HashSet<MessageId>,
1545        cx: &mut ModelContext<Self>,
1546    ) -> Vec<MessageAnchor> {
1547        let mut user_messages = Vec::new();
1548
1549        let last_message_id = if let Some(last_message_id) =
1550            self.message_anchors.iter().rev().find_map(|message| {
1551                message
1552                    .start
1553                    .is_valid(self.buffer.read(cx))
1554                    .then_some(message.id)
1555            }) {
1556            last_message_id
1557        } else {
1558            return Default::default();
1559        };
1560
1561        let mut should_assist = false;
1562        for selected_message_id in selected_messages {
1563            let selected_message_role =
1564                if let Some(metadata) = self.messages_metadata.get(&selected_message_id) {
1565                    metadata.role
1566                } else {
1567                    continue;
1568                };
1569
1570            if selected_message_role == Role::Assistant {
1571                if let Some(user_message) = self.insert_message_after(
1572                    selected_message_id,
1573                    Role::User,
1574                    MessageStatus::Done,
1575                    cx,
1576                ) {
1577                    user_messages.push(user_message);
1578                }
1579            } else {
1580                should_assist = true;
1581            }
1582        }
1583
1584        if should_assist {
1585            if !self.completion_provider.has_credentials() {
1586                return Default::default();
1587            }
1588
1589            let request: Box<dyn CompletionRequest> = Box::new(OpenAIRequest {
1590                model: self.model.full_name().to_string(),
1591                messages: self
1592                    .messages(cx)
1593                    .filter(|message| matches!(message.status, MessageStatus::Done))
1594                    .map(|message| message.to_open_ai_message(self.buffer.read(cx)))
1595                    .collect(),
1596                stream: true,
1597                stop: vec![],
1598                temperature: 1.0,
1599            });
1600
1601            let stream = self.completion_provider.complete(request);
1602            let assistant_message = self
1603                .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1604                .unwrap();
1605
1606            // Queue up the user's next reply.
1607            let user_message = self
1608                .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
1609                .unwrap();
1610            user_messages.push(user_message);
1611
1612            let task = cx.spawn({
1613                |this, mut cx| async move {
1614                    let assistant_message_id = assistant_message.id;
1615                    let stream_completion = async {
1616                        let mut messages = stream.await?;
1617
1618                        while let Some(message) = messages.next().await {
1619                            let text = message?;
1620
1621                            this.update(&mut cx, |this, cx| {
1622                                let message_ix = this
1623                                    .message_anchors
1624                                    .iter()
1625                                    .position(|message| message.id == assistant_message_id)?;
1626                                this.buffer.update(cx, |buffer, cx| {
1627                                    let offset = this.message_anchors[message_ix + 1..]
1628                                        .iter()
1629                                        .find(|message| message.start.is_valid(buffer))
1630                                        .map_or(buffer.len(), |message| {
1631                                            message.start.to_offset(buffer).saturating_sub(1)
1632                                        });
1633                                    buffer.edit([(offset..offset, text)], None, cx);
1634                                });
1635                                cx.emit(ConversationEvent::StreamedCompletion);
1636
1637                                Some(())
1638                            })?;
1639                            smol::future::yield_now().await;
1640                        }
1641
1642                        this.update(&mut cx, |this, cx| {
1643                            this.pending_completions
1644                                .retain(|completion| completion.id != this.completion_count);
1645                            this.summarize(cx);
1646                        })?;
1647
1648                        anyhow::Ok(())
1649                    };
1650
1651                    let result = stream_completion.await;
1652
1653                    this.update(&mut cx, |this, cx| {
1654                        if let Some(metadata) =
1655                            this.messages_metadata.get_mut(&assistant_message.id)
1656                        {
1657                            match result {
1658                                Ok(_) => {
1659                                    metadata.status = MessageStatus::Done;
1660                                }
1661                                Err(error) => {
1662                                    metadata.status = MessageStatus::Error(SharedString::from(
1663                                        error.to_string().trim().to_string(),
1664                                    ));
1665                                }
1666                            }
1667                            cx.notify();
1668                        }
1669                    })
1670                    .ok();
1671                }
1672            });
1673
1674            self.pending_completions.push(PendingCompletion {
1675                id: post_inc(&mut self.completion_count),
1676                _task: task,
1677            });
1678        }
1679
1680        user_messages
1681    }
1682
1683    fn cancel_last_assist(&mut self) -> bool {
1684        self.pending_completions.pop().is_some()
1685    }
1686
1687    fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
1688        for id in ids {
1689            if let Some(metadata) = self.messages_metadata.get_mut(&id) {
1690                metadata.role.cycle();
1691                cx.emit(ConversationEvent::MessagesEdited);
1692                cx.notify();
1693            }
1694        }
1695    }
1696
1697    fn insert_message_after(
1698        &mut self,
1699        message_id: MessageId,
1700        role: Role,
1701        status: MessageStatus,
1702        cx: &mut ModelContext<Self>,
1703    ) -> Option<MessageAnchor> {
1704        if let Some(prev_message_ix) = self
1705            .message_anchors
1706            .iter()
1707            .position(|message| message.id == message_id)
1708        {
1709            // Find the next valid message after the one we were given.
1710            let mut next_message_ix = prev_message_ix + 1;
1711            while let Some(next_message) = self.message_anchors.get(next_message_ix) {
1712                if next_message.start.is_valid(self.buffer.read(cx)) {
1713                    break;
1714                }
1715                next_message_ix += 1;
1716            }
1717
1718            let start = self.buffer.update(cx, |buffer, cx| {
1719                let offset = self
1720                    .message_anchors
1721                    .get(next_message_ix)
1722                    .map_or(buffer.len(), |message| message.start.to_offset(buffer) - 1);
1723                buffer.edit([(offset..offset, "\n")], None, cx);
1724                buffer.anchor_before(offset + 1)
1725            });
1726            let message = MessageAnchor {
1727                id: MessageId(post_inc(&mut self.next_message_id.0)),
1728                start,
1729            };
1730            self.message_anchors
1731                .insert(next_message_ix, message.clone());
1732            self.messages_metadata.insert(
1733                message.id,
1734                MessageMetadata {
1735                    role,
1736                    sent_at: Local::now(),
1737                    status,
1738                },
1739            );
1740            cx.emit(ConversationEvent::MessagesEdited);
1741            Some(message)
1742        } else {
1743            None
1744        }
1745    }
1746
1747    fn split_message(
1748        &mut self,
1749        range: Range<usize>,
1750        cx: &mut ModelContext<Self>,
1751    ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
1752        let start_message = self.message_for_offset(range.start, cx);
1753        let end_message = self.message_for_offset(range.end, cx);
1754        if let Some((start_message, end_message)) = start_message.zip(end_message) {
1755            // Prevent splitting when range spans multiple messages.
1756            if start_message.id != end_message.id {
1757                return (None, None);
1758            }
1759
1760            let message = start_message;
1761            let role = message.role;
1762            let mut edited_buffer = false;
1763
1764            let mut suffix_start = None;
1765            if range.start > message.offset_range.start && range.end < message.offset_range.end - 1
1766            {
1767                if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
1768                    suffix_start = Some(range.end + 1);
1769                } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
1770                    suffix_start = Some(range.end);
1771                }
1772            }
1773
1774            let suffix = if let Some(suffix_start) = suffix_start {
1775                MessageAnchor {
1776                    id: MessageId(post_inc(&mut self.next_message_id.0)),
1777                    start: self.buffer.read(cx).anchor_before(suffix_start),
1778                }
1779            } else {
1780                self.buffer.update(cx, |buffer, cx| {
1781                    buffer.edit([(range.end..range.end, "\n")], None, cx);
1782                });
1783                edited_buffer = true;
1784                MessageAnchor {
1785                    id: MessageId(post_inc(&mut self.next_message_id.0)),
1786                    start: self.buffer.read(cx).anchor_before(range.end + 1),
1787                }
1788            };
1789
1790            self.message_anchors
1791                .insert(message.index_range.end + 1, suffix.clone());
1792            self.messages_metadata.insert(
1793                suffix.id,
1794                MessageMetadata {
1795                    role,
1796                    sent_at: Local::now(),
1797                    status: MessageStatus::Done,
1798                },
1799            );
1800
1801            let new_messages =
1802                if range.start == range.end || range.start == message.offset_range.start {
1803                    (None, Some(suffix))
1804                } else {
1805                    let mut prefix_end = None;
1806                    if range.start > message.offset_range.start
1807                        && range.end < message.offset_range.end - 1
1808                    {
1809                        if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
1810                            prefix_end = Some(range.start + 1);
1811                        } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
1812                            == Some('\n')
1813                        {
1814                            prefix_end = Some(range.start);
1815                        }
1816                    }
1817
1818                    let selection = if let Some(prefix_end) = prefix_end {
1819                        cx.emit(ConversationEvent::MessagesEdited);
1820                        MessageAnchor {
1821                            id: MessageId(post_inc(&mut self.next_message_id.0)),
1822                            start: self.buffer.read(cx).anchor_before(prefix_end),
1823                        }
1824                    } else {
1825                        self.buffer.update(cx, |buffer, cx| {
1826                            buffer.edit([(range.start..range.start, "\n")], None, cx)
1827                        });
1828                        edited_buffer = true;
1829                        MessageAnchor {
1830                            id: MessageId(post_inc(&mut self.next_message_id.0)),
1831                            start: self.buffer.read(cx).anchor_before(range.end + 1),
1832                        }
1833                    };
1834
1835                    self.message_anchors
1836                        .insert(message.index_range.end + 1, selection.clone());
1837                    self.messages_metadata.insert(
1838                        selection.id,
1839                        MessageMetadata {
1840                            role,
1841                            sent_at: Local::now(),
1842                            status: MessageStatus::Done,
1843                        },
1844                    );
1845                    (Some(selection), Some(suffix))
1846                };
1847
1848            if !edited_buffer {
1849                cx.emit(ConversationEvent::MessagesEdited);
1850            }
1851            new_messages
1852        } else {
1853            (None, None)
1854        }
1855    }
1856
1857    fn summarize(&mut self, cx: &mut ModelContext<Self>) {
1858        if self.message_anchors.len() >= 2 && self.summary.is_none() {
1859            if !self.completion_provider.has_credentials() {
1860                return;
1861            }
1862
1863            let messages = self
1864                .messages(cx)
1865                .take(2)
1866                .map(|message| message.to_open_ai_message(self.buffer.read(cx)))
1867                .chain(Some(RequestMessage {
1868                    role: Role::User,
1869                    content: "Summarize the conversation into a short title without punctuation"
1870                        .into(),
1871                }));
1872            let request: Box<dyn CompletionRequest> = Box::new(OpenAIRequest {
1873                model: self.model.full_name().to_string(),
1874                messages: messages.collect(),
1875                stream: true,
1876                stop: vec![],
1877                temperature: 1.0,
1878            });
1879
1880            let stream = self.completion_provider.complete(request);
1881            self.pending_summary = cx.spawn(|this, mut cx| {
1882                async move {
1883                    let mut messages = stream.await?;
1884
1885                    while let Some(message) = messages.next().await {
1886                        let text = message?;
1887                        this.update(&mut cx, |this, cx| {
1888                            this.summary
1889                                .get_or_insert(Default::default())
1890                                .text
1891                                .push_str(&text);
1892                            cx.emit(ConversationEvent::SummaryChanged);
1893                        })?;
1894                    }
1895
1896                    this.update(&mut cx, |this, cx| {
1897                        if let Some(summary) = this.summary.as_mut() {
1898                            summary.done = true;
1899                            cx.emit(ConversationEvent::SummaryChanged);
1900                        }
1901                    })?;
1902
1903                    anyhow::Ok(())
1904                }
1905                .log_err()
1906            });
1907        }
1908    }
1909
1910    fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
1911        self.messages_for_offsets([offset], cx).pop()
1912    }
1913
1914    fn messages_for_offsets(
1915        &self,
1916        offsets: impl IntoIterator<Item = usize>,
1917        cx: &AppContext,
1918    ) -> Vec<Message> {
1919        let mut result = Vec::new();
1920
1921        let mut messages = self.messages(cx).peekable();
1922        let mut offsets = offsets.into_iter().peekable();
1923        let mut current_message = messages.next();
1924        while let Some(offset) = offsets.next() {
1925            // Locate the message that contains the offset.
1926            while current_message.as_ref().map_or(false, |message| {
1927                !message.offset_range.contains(&offset) && messages.peek().is_some()
1928            }) {
1929                current_message = messages.next();
1930            }
1931            let Some(message) = current_message.as_ref() else {
1932                break;
1933            };
1934
1935            // Skip offsets that are in the same message.
1936            while offsets.peek().map_or(false, |offset| {
1937                message.offset_range.contains(offset) || messages.peek().is_none()
1938            }) {
1939                offsets.next();
1940            }
1941
1942            result.push(message.clone());
1943        }
1944        result
1945    }
1946
1947    fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
1948        let buffer = self.buffer.read(cx);
1949        let mut message_anchors = self.message_anchors.iter().enumerate().peekable();
1950        iter::from_fn(move || {
1951            while let Some((start_ix, message_anchor)) = message_anchors.next() {
1952                let metadata = self.messages_metadata.get(&message_anchor.id)?;
1953                let message_start = message_anchor.start.to_offset(buffer);
1954                let mut message_end = None;
1955                let mut end_ix = start_ix;
1956                while let Some((_, next_message)) = message_anchors.peek() {
1957                    if next_message.start.is_valid(buffer) {
1958                        message_end = Some(next_message.start);
1959                        break;
1960                    } else {
1961                        end_ix += 1;
1962                        message_anchors.next();
1963                    }
1964                }
1965                let message_end = message_end
1966                    .unwrap_or(language::Anchor::MAX)
1967                    .to_offset(buffer);
1968                return Some(Message {
1969                    index_range: start_ix..end_ix,
1970                    offset_range: message_start..message_end,
1971                    id: message_anchor.id,
1972                    anchor: message_anchor.start,
1973                    role: metadata.role,
1974                    sent_at: metadata.sent_at,
1975                    status: metadata.status.clone(),
1976                });
1977            }
1978            None
1979        })
1980    }
1981
1982    fn save(
1983        &mut self,
1984        debounce: Option<Duration>,
1985        fs: Arc<dyn Fs>,
1986        cx: &mut ModelContext<Conversation>,
1987    ) {
1988        self.pending_save = cx.spawn(|this, mut cx| async move {
1989            if let Some(debounce) = debounce {
1990                cx.background_executor().timer(debounce).await;
1991            }
1992
1993            let (old_path, summary) = this.read_with(&cx, |this, _| {
1994                let path = this.path.clone();
1995                let summary = if let Some(summary) = this.summary.as_ref() {
1996                    if summary.done {
1997                        Some(summary.text.clone())
1998                    } else {
1999                        None
2000                    }
2001                } else {
2002                    None
2003                };
2004                (path, summary)
2005            })?;
2006
2007            if let Some(summary) = summary {
2008                let conversation = this.read_with(&cx, |this, cx| this.serialize(cx))?;
2009                let path = if let Some(old_path) = old_path {
2010                    old_path
2011                } else {
2012                    let mut discriminant = 1;
2013                    let mut new_path;
2014                    loop {
2015                        new_path = CONVERSATIONS_DIR.join(&format!(
2016                            "{} - {}.zed.json",
2017                            summary.trim(),
2018                            discriminant
2019                        ));
2020                        if fs.is_file(&new_path).await {
2021                            discriminant += 1;
2022                        } else {
2023                            break;
2024                        }
2025                    }
2026                    new_path
2027                };
2028
2029                fs.create_dir(CONVERSATIONS_DIR.as_ref()).await?;
2030                fs.atomic_write(path.clone(), serde_json::to_string(&conversation).unwrap())
2031                    .await?;
2032                this.update(&mut cx, |this, _| this.path = Some(path))?;
2033            }
2034
2035            Ok(())
2036        });
2037    }
2038}
2039
2040struct PendingCompletion {
2041    id: usize,
2042    _task: Task<()>,
2043}
2044
2045enum ConversationEditorEvent {
2046    TabContentChanged,
2047}
2048
2049#[derive(Copy, Clone, Debug, PartialEq)]
2050struct ScrollPosition {
2051    offset_before_cursor: gpui::Point<f32>,
2052    cursor: Anchor,
2053}
2054
2055struct ConversationEditor {
2056    conversation: Model<Conversation>,
2057    fs: Arc<dyn Fs>,
2058    workspace: WeakView<Workspace>,
2059    editor: View<Editor>,
2060    blocks: HashSet<BlockId>,
2061    scroll_position: Option<ScrollPosition>,
2062    _subscriptions: Vec<Subscription>,
2063}
2064
2065impl ConversationEditor {
2066    fn new(
2067        completion_provider: Arc<dyn CompletionProvider>,
2068        language_registry: Arc<LanguageRegistry>,
2069        fs: Arc<dyn Fs>,
2070        workspace: WeakView<Workspace>,
2071        cx: &mut ViewContext<Self>,
2072    ) -> Self {
2073        let conversation =
2074            cx.build_model(|cx| Conversation::new(language_registry, cx, completion_provider));
2075        Self::for_conversation(conversation, fs, workspace, cx)
2076    }
2077
2078    fn for_conversation(
2079        conversation: Model<Conversation>,
2080        fs: Arc<dyn Fs>,
2081        workspace: WeakView<Workspace>,
2082        cx: &mut ViewContext<Self>,
2083    ) -> Self {
2084        let editor = cx.build_view(|cx| {
2085            let mut editor = Editor::for_buffer(conversation.read(cx).buffer.clone(), None, cx);
2086            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
2087            editor.set_show_gutter(false, cx);
2088            editor.set_show_wrap_guides(false, cx);
2089            editor
2090        });
2091
2092        let _subscriptions = vec![
2093            cx.observe(&conversation, |_, _, cx| cx.notify()),
2094            cx.subscribe(&conversation, Self::handle_conversation_event),
2095            cx.subscribe(&editor, Self::handle_editor_event),
2096        ];
2097
2098        let mut this = Self {
2099            conversation,
2100            editor,
2101            blocks: Default::default(),
2102            scroll_position: None,
2103            fs,
2104            workspace,
2105            _subscriptions,
2106        };
2107        this.update_message_headers(cx);
2108        this
2109    }
2110
2111    fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
2112        report_assistant_event(
2113            self.workspace.clone(),
2114            self.conversation.read(cx).id.clone(),
2115            AssistantKind::Panel,
2116            cx,
2117        );
2118
2119        let cursors = self.cursors(cx);
2120
2121        let user_messages = self.conversation.update(cx, |conversation, cx| {
2122            let selected_messages = conversation
2123                .messages_for_offsets(cursors, cx)
2124                .into_iter()
2125                .map(|message| message.id)
2126                .collect();
2127            conversation.assist(selected_messages, cx)
2128        });
2129        let new_selections = user_messages
2130            .iter()
2131            .map(|message| {
2132                let cursor = message
2133                    .start
2134                    .to_offset(self.conversation.read(cx).buffer.read(cx));
2135                cursor..cursor
2136            })
2137            .collect::<Vec<_>>();
2138        if !new_selections.is_empty() {
2139            self.editor.update(cx, |editor, cx| {
2140                editor.change_selections(
2141                    Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
2142                    cx,
2143                    |selections| selections.select_ranges(new_selections),
2144                );
2145            });
2146            // Avoid scrolling to the new cursor position so the assistant's output is stable.
2147            cx.defer(|this, _| this.scroll_position = None);
2148        }
2149    }
2150
2151    fn cancel_last_assist(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
2152        if !self
2153            .conversation
2154            .update(cx, |conversation, _| conversation.cancel_last_assist())
2155        {
2156            cx.propagate();
2157        }
2158    }
2159
2160    fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
2161        let cursors = self.cursors(cx);
2162        self.conversation.update(cx, |conversation, cx| {
2163            let messages = conversation
2164                .messages_for_offsets(cursors, cx)
2165                .into_iter()
2166                .map(|message| message.id)
2167                .collect();
2168            conversation.cycle_message_roles(messages, cx)
2169        });
2170    }
2171
2172    fn cursors(&self, cx: &AppContext) -> Vec<usize> {
2173        let selections = self.editor.read(cx).selections.all::<usize>(cx);
2174        selections
2175            .into_iter()
2176            .map(|selection| selection.head())
2177            .collect()
2178    }
2179
2180    fn handle_conversation_event(
2181        &mut self,
2182        _: Model<Conversation>,
2183        event: &ConversationEvent,
2184        cx: &mut ViewContext<Self>,
2185    ) {
2186        match event {
2187            ConversationEvent::MessagesEdited => {
2188                self.update_message_headers(cx);
2189                self.conversation.update(cx, |conversation, cx| {
2190                    conversation.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
2191                });
2192            }
2193            ConversationEvent::SummaryChanged => {
2194                cx.emit(ConversationEditorEvent::TabContentChanged);
2195                self.conversation.update(cx, |conversation, cx| {
2196                    conversation.save(None, self.fs.clone(), cx);
2197                });
2198            }
2199            ConversationEvent::StreamedCompletion => {
2200                self.editor.update(cx, |editor, cx| {
2201                    if let Some(scroll_position) = self.scroll_position {
2202                        let snapshot = editor.snapshot(cx);
2203                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
2204                        let scroll_top =
2205                            cursor_point.row() as f32 - scroll_position.offset_before_cursor.y;
2206                        editor.set_scroll_position(
2207                            point(scroll_position.offset_before_cursor.x, scroll_top),
2208                            cx,
2209                        );
2210                    }
2211                });
2212            }
2213        }
2214    }
2215
2216    fn handle_editor_event(
2217        &mut self,
2218        _: View<Editor>,
2219        event: &EditorEvent,
2220        cx: &mut ViewContext<Self>,
2221    ) {
2222        match event {
2223            EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2224                let cursor_scroll_position = self.cursor_scroll_position(cx);
2225                if *autoscroll {
2226                    self.scroll_position = cursor_scroll_position;
2227                } else if self.scroll_position != cursor_scroll_position {
2228                    self.scroll_position = None;
2229                }
2230            }
2231            EditorEvent::SelectionsChanged { .. } => {
2232                self.scroll_position = self.cursor_scroll_position(cx);
2233            }
2234            _ => {}
2235        }
2236    }
2237
2238    fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2239        self.editor.update(cx, |editor, cx| {
2240            let snapshot = editor.snapshot(cx);
2241            let cursor = editor.selections.newest_anchor().head();
2242            let cursor_row = cursor.to_display_point(&snapshot.display_snapshot).row() as f32;
2243            let scroll_position = editor
2244                .scroll_manager
2245                .anchor()
2246                .scroll_position(&snapshot.display_snapshot);
2247
2248            let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2249            if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2250                Some(ScrollPosition {
2251                    cursor,
2252                    offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2253                })
2254            } else {
2255                None
2256            }
2257        })
2258    }
2259
2260    fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2261        self.editor.update(cx, |editor, cx| {
2262            let buffer = editor.buffer().read(cx).snapshot(cx);
2263            let excerpt_id = *buffer.as_singleton().unwrap().0;
2264            let old_blocks = std::mem::take(&mut self.blocks);
2265            let new_blocks = self
2266                .conversation
2267                .read(cx)
2268                .messages(cx)
2269                .map(|message| BlockProperties {
2270                    position: buffer.anchor_in_excerpt(excerpt_id, message.anchor),
2271                    height: 2,
2272                    style: BlockStyle::Sticky,
2273                    render: Arc::new({
2274                        let conversation = self.conversation.clone();
2275                        move |_cx| {
2276                            let message_id = message.id;
2277                            let sender = ButtonLike::new("role")
2278                                .child(match message.role {
2279                                    Role::User => Label::new("You").color(Color::Default),
2280                                    Role::Assistant => {
2281                                        Label::new("Assistant").color(Color::Modified)
2282                                    }
2283                                    Role::System => Label::new("System").color(Color::Warning),
2284                                })
2285                                .tooltip(|cx| {
2286                                    Tooltip::with_meta(
2287                                        "Toggle message role",
2288                                        None,
2289                                        "Available roles: You (User), Assistant, System",
2290                                        cx,
2291                                    )
2292                                })
2293                                .on_click({
2294                                    let conversation = conversation.clone();
2295                                    move |_, cx| {
2296                                        conversation.update(cx, |conversation, cx| {
2297                                            conversation.cycle_message_roles(
2298                                                HashSet::from_iter(Some(message_id)),
2299                                                cx,
2300                                            )
2301                                        })
2302                                    }
2303                                });
2304
2305                            h_stack()
2306                                .id(("message_header", message_id.0))
2307                                .h_11()
2308                                .gap_1()
2309                                .p_1()
2310                                .child(sender)
2311                                // TODO: Only show this if the message if the message has been sent
2312                                .child(
2313                                    Label::new(
2314                                        FormatDistance::from_now(DateTimeType::Local(
2315                                            message.sent_at,
2316                                        ))
2317                                        .hide_prefix(true)
2318                                        .add_suffix(true)
2319                                        .to_string(),
2320                                    )
2321                                    .color(Color::Muted),
2322                                )
2323                                .children(
2324                                    if let MessageStatus::Error(error) = message.status.clone() {
2325                                        Some(
2326                                            div()
2327                                                .id("error")
2328                                                .tooltip(move |cx| Tooltip::text(error.clone(), cx))
2329                                                .child(IconElement::new(Icon::XCircle)),
2330                                        )
2331                                    } else {
2332                                        None
2333                                    },
2334                                )
2335                                .into_any_element()
2336                        }
2337                    }),
2338                    disposition: BlockDisposition::Above,
2339                })
2340                .collect::<Vec<_>>();
2341
2342            editor.remove_blocks(old_blocks, None, cx);
2343            let ids = editor.insert_blocks(new_blocks, None, cx);
2344            self.blocks = HashSet::from_iter(ids);
2345        });
2346    }
2347
2348    fn quote_selection(
2349        workspace: &mut Workspace,
2350        _: &QuoteSelection,
2351        cx: &mut ViewContext<Workspace>,
2352    ) {
2353        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2354            return;
2355        };
2356        let Some(editor) = workspace
2357            .active_item(cx)
2358            .and_then(|item| item.act_as::<Editor>(cx))
2359        else {
2360            return;
2361        };
2362
2363        let editor = editor.read(cx);
2364        let range = editor.selections.newest::<usize>(cx).range();
2365        let buffer = editor.buffer().read(cx).snapshot(cx);
2366        let start_language = buffer.language_at(range.start);
2367        let end_language = buffer.language_at(range.end);
2368        let language_name = if start_language == end_language {
2369            start_language.map(|language| language.name())
2370        } else {
2371            None
2372        };
2373        let language_name = language_name.as_deref().unwrap_or("").to_lowercase();
2374
2375        let selected_text = buffer.text_for_range(range).collect::<String>();
2376        let text = if selected_text.is_empty() {
2377            None
2378        } else {
2379            Some(if language_name == "markdown" {
2380                selected_text
2381                    .lines()
2382                    .map(|line| format!("> {}", line))
2383                    .collect::<Vec<_>>()
2384                    .join("\n")
2385            } else {
2386                format!("```{language_name}\n{selected_text}\n```")
2387            })
2388        };
2389
2390        // Activate the panel
2391        if !panel.focus_handle(cx).contains_focused(cx) {
2392            workspace.toggle_panel_focus::<AssistantPanel>(cx);
2393        }
2394
2395        if let Some(text) = text {
2396            panel.update(cx, |panel, cx| {
2397                let conversation = panel
2398                    .active_editor()
2399                    .cloned()
2400                    .unwrap_or_else(|| panel.new_conversation(cx));
2401                conversation.update(cx, |conversation, cx| {
2402                    conversation
2403                        .editor
2404                        .update(cx, |editor, cx| editor.insert(&text, cx))
2405                });
2406            });
2407        }
2408    }
2409
2410    fn copy(&mut self, _: &editor::Copy, cx: &mut ViewContext<Self>) {
2411        let editor = self.editor.read(cx);
2412        let conversation = self.conversation.read(cx);
2413        if editor.selections.count() == 1 {
2414            let selection = editor.selections.newest::<usize>(cx);
2415            let mut copied_text = String::new();
2416            let mut spanned_messages = 0;
2417            for message in conversation.messages(cx) {
2418                if message.offset_range.start >= selection.range().end {
2419                    break;
2420                } else if message.offset_range.end >= selection.range().start {
2421                    let range = cmp::max(message.offset_range.start, selection.range().start)
2422                        ..cmp::min(message.offset_range.end, selection.range().end);
2423                    if !range.is_empty() {
2424                        spanned_messages += 1;
2425                        write!(&mut copied_text, "## {}\n\n", message.role).unwrap();
2426                        for chunk in conversation.buffer.read(cx).text_for_range(range) {
2427                            copied_text.push_str(&chunk);
2428                        }
2429                        copied_text.push('\n');
2430                    }
2431                }
2432            }
2433
2434            if spanned_messages > 1 {
2435                cx.write_to_clipboard(ClipboardItem::new(copied_text));
2436                return;
2437            }
2438        }
2439
2440        cx.propagate();
2441    }
2442
2443    fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
2444        self.conversation.update(cx, |conversation, cx| {
2445            let selections = self.editor.read(cx).selections.disjoint_anchors();
2446            for selection in selections.into_iter() {
2447                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2448                let range = selection
2449                    .map(|endpoint| endpoint.to_offset(&buffer))
2450                    .range();
2451                conversation.split_message(range, cx);
2452            }
2453        });
2454    }
2455
2456    fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
2457        self.conversation.update(cx, |conversation, cx| {
2458            conversation.save(None, self.fs.clone(), cx)
2459        });
2460    }
2461
2462    fn cycle_model(&mut self, cx: &mut ViewContext<Self>) {
2463        self.conversation.update(cx, |conversation, cx| {
2464            let new_model = conversation.model.cycle();
2465            conversation.set_model(new_model, cx);
2466        });
2467    }
2468
2469    fn title(&self, cx: &AppContext) -> String {
2470        self.conversation
2471            .read(cx)
2472            .summary
2473            .as_ref()
2474            .map(|summary| summary.text.clone())
2475            .unwrap_or_else(|| "New Conversation".into())
2476    }
2477
2478    fn render_current_model(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2479        Button::new(
2480            "current_model",
2481            self.conversation.read(cx).model.short_name(),
2482        )
2483        .style(ButtonStyle::Filled)
2484        .tooltip(move |cx| Tooltip::text("Change Model", cx))
2485        .on_click(cx.listener(|this, _, cx| this.cycle_model(cx)))
2486    }
2487
2488    fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
2489        let remaining_tokens = self.conversation.read(cx).remaining_tokens()?;
2490        let remaining_tokens_color = if remaining_tokens <= 0 {
2491            Color::Error
2492        } else if remaining_tokens <= 500 {
2493            Color::Warning
2494        } else {
2495            Color::Default
2496        };
2497        Some(Label::new(remaining_tokens.to_string()).color(remaining_tokens_color))
2498    }
2499}
2500
2501impl EventEmitter<ConversationEditorEvent> for ConversationEditor {}
2502
2503impl Render for ConversationEditor {
2504    type Element = Div;
2505
2506    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2507        div()
2508            .key_context("ConversationEditor")
2509            .capture_action(cx.listener(ConversationEditor::cancel_last_assist))
2510            .capture_action(cx.listener(ConversationEditor::save))
2511            .capture_action(cx.listener(ConversationEditor::copy))
2512            .capture_action(cx.listener(ConversationEditor::cycle_message_role))
2513            .on_action(cx.listener(ConversationEditor::assist))
2514            .on_action(cx.listener(ConversationEditor::split))
2515            .size_full()
2516            .relative()
2517            .child(
2518                div()
2519                    .size_full()
2520                    .pl_2()
2521                    .bg(cx.theme().colors().editor_background)
2522                    .child(self.editor.clone()),
2523            )
2524            .child(
2525                h_stack()
2526                    .absolute()
2527                    .gap_1()
2528                    .top_3()
2529                    .right_5()
2530                    .child(self.render_current_model(cx))
2531                    .children(self.render_remaining_tokens(cx)),
2532            )
2533    }
2534}
2535
2536impl FocusableView for ConversationEditor {
2537    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
2538        self.editor.focus_handle(cx)
2539    }
2540}
2541
2542#[derive(Clone, Debug)]
2543struct MessageAnchor {
2544    id: MessageId,
2545    start: language::Anchor,
2546}
2547
2548#[derive(Clone, Debug)]
2549pub struct Message {
2550    offset_range: Range<usize>,
2551    index_range: Range<usize>,
2552    id: MessageId,
2553    anchor: language::Anchor,
2554    role: Role,
2555    sent_at: DateTime<Local>,
2556    status: MessageStatus,
2557}
2558
2559impl Message {
2560    fn to_open_ai_message(&self, buffer: &Buffer) -> RequestMessage {
2561        let content = buffer
2562            .text_for_range(self.offset_range.clone())
2563            .collect::<String>();
2564        RequestMessage {
2565            role: self.role,
2566            content: content.trim_end().into(),
2567        }
2568    }
2569}
2570
2571enum InlineAssistantEvent {
2572    Confirmed {
2573        prompt: String,
2574        include_conversation: bool,
2575        retrieve_context: bool,
2576    },
2577    Canceled,
2578    Dismissed,
2579    IncludeConversationToggled {
2580        include_conversation: bool,
2581    },
2582    RetrieveContextToggled {
2583        retrieve_context: bool,
2584    },
2585}
2586
2587struct InlineAssistant {
2588    id: usize,
2589    prompt_editor: View<Editor>,
2590    workspace: WeakView<Workspace>,
2591    confirmed: bool,
2592    include_conversation: bool,
2593    measurements: Rc<Cell<BlockMeasurements>>,
2594    prompt_history: VecDeque<String>,
2595    prompt_history_ix: Option<usize>,
2596    pending_prompt: String,
2597    codegen: Model<Codegen>,
2598    _subscriptions: Vec<Subscription>,
2599    retrieve_context: bool,
2600    semantic_index: Option<Model<SemanticIndex>>,
2601    semantic_permissioned: Option<bool>,
2602    project: WeakModel<Project>,
2603    maintain_rate_limit: Option<Task<()>>,
2604}
2605
2606impl EventEmitter<InlineAssistantEvent> for InlineAssistant {}
2607
2608impl Render for InlineAssistant {
2609    type Element = Div;
2610
2611    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2612        let measurements = self.measurements.get();
2613        h_stack()
2614            .w_full()
2615            .py_2()
2616            .border_y_1()
2617            .border_color(cx.theme().colors().border)
2618            .on_action(cx.listener(Self::confirm))
2619            .on_action(cx.listener(Self::cancel))
2620            .on_action(cx.listener(Self::toggle_include_conversation))
2621            .on_action(cx.listener(Self::toggle_retrieve_context))
2622            .on_action(cx.listener(Self::move_up))
2623            .on_action(cx.listener(Self::move_down))
2624            .child(
2625                h_stack()
2626                    .justify_center()
2627                    .w(measurements.gutter_width)
2628                    .child(
2629                        IconButton::new("include_conversation", Icon::Ai)
2630                            .on_click(cx.listener(|this, _, cx| {
2631                                this.toggle_include_conversation(&ToggleIncludeConversation, cx)
2632                            }))
2633                            .selected(self.include_conversation)
2634                            .tooltip(|cx| {
2635                                Tooltip::for_action(
2636                                    "Include Conversation",
2637                                    &ToggleIncludeConversation,
2638                                    cx,
2639                                )
2640                            }),
2641                    )
2642                    .children(if SemanticIndex::enabled(cx) {
2643                        Some(
2644                            IconButton::new("retrieve_context", Icon::MagnifyingGlass)
2645                                .on_click(cx.listener(|this, _, cx| {
2646                                    this.toggle_retrieve_context(&ToggleRetrieveContext, cx)
2647                                }))
2648                                .selected(self.retrieve_context)
2649                                .tooltip(|cx| {
2650                                    Tooltip::for_action(
2651                                        "Retrieve Context",
2652                                        &ToggleRetrieveContext,
2653                                        cx,
2654                                    )
2655                                }),
2656                        )
2657                    } else {
2658                        None
2659                    })
2660                    .children(if let Some(error) = self.codegen.read(cx).error() {
2661                        let error_message = SharedString::from(error.to_string());
2662                        Some(
2663                            div()
2664                                .id("error")
2665                                .tooltip(move |cx| Tooltip::text(error_message.clone(), cx))
2666                                .child(IconElement::new(Icon::XCircle).color(Color::Error)),
2667                        )
2668                    } else {
2669                        None
2670                    }),
2671            )
2672            .child(
2673                h_stack()
2674                    .w_full()
2675                    .ml(measurements.anchor_x - measurements.gutter_width)
2676                    .child(self.render_prompt_editor(cx)),
2677            )
2678            .children(if self.retrieve_context {
2679                self.retrieve_context_status(cx)
2680            } else {
2681                None
2682            })
2683    }
2684}
2685
2686impl FocusableView for InlineAssistant {
2687    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
2688        self.prompt_editor.focus_handle(cx)
2689    }
2690}
2691
2692impl InlineAssistant {
2693    fn new(
2694        id: usize,
2695        measurements: Rc<Cell<BlockMeasurements>>,
2696        include_conversation: bool,
2697        prompt_history: VecDeque<String>,
2698        codegen: Model<Codegen>,
2699        workspace: WeakView<Workspace>,
2700        cx: &mut ViewContext<Self>,
2701        retrieve_context: bool,
2702        semantic_index: Option<Model<SemanticIndex>>,
2703        project: Model<Project>,
2704    ) -> Self {
2705        let prompt_editor = cx.build_view(|cx| {
2706            let mut editor = Editor::single_line(cx);
2707            let placeholder = match codegen.read(cx).kind() {
2708                CodegenKind::Transform { .. } => "Enter transformation prompt…",
2709                CodegenKind::Generate { .. } => "Enter generation prompt…",
2710            };
2711            editor.set_placeholder_text(placeholder, cx);
2712            editor
2713        });
2714        cx.focus_view(&prompt_editor);
2715
2716        let mut subscriptions = vec![
2717            cx.observe(&codegen, Self::handle_codegen_changed),
2718            cx.subscribe(&prompt_editor, Self::handle_prompt_editor_events),
2719        ];
2720
2721        if let Some(semantic_index) = semantic_index.clone() {
2722            subscriptions.push(cx.observe(&semantic_index, Self::semantic_index_changed));
2723        }
2724
2725        let assistant = Self {
2726            id,
2727            prompt_editor,
2728            workspace,
2729            confirmed: false,
2730            include_conversation,
2731            measurements,
2732            prompt_history,
2733            prompt_history_ix: None,
2734            pending_prompt: String::new(),
2735            codegen,
2736            _subscriptions: subscriptions,
2737            retrieve_context,
2738            semantic_permissioned: None,
2739            semantic_index,
2740            project: project.downgrade(),
2741            maintain_rate_limit: None,
2742        };
2743
2744        assistant.index_project(cx).log_err();
2745
2746        assistant
2747    }
2748
2749    fn semantic_permissioned(&self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
2750        if let Some(value) = self.semantic_permissioned {
2751            return Task::ready(Ok(value));
2752        }
2753
2754        let Some(project) = self.project.upgrade() else {
2755            return Task::ready(Err(anyhow!("project was dropped")));
2756        };
2757
2758        self.semantic_index
2759            .as_ref()
2760            .map(|semantic| {
2761                semantic.update(cx, |this, cx| this.project_previously_indexed(&project, cx))
2762            })
2763            .unwrap_or(Task::ready(Ok(false)))
2764    }
2765
2766    fn handle_prompt_editor_events(
2767        &mut self,
2768        _: View<Editor>,
2769        event: &EditorEvent,
2770        cx: &mut ViewContext<Self>,
2771    ) {
2772        if let EditorEvent::Edited = event {
2773            self.pending_prompt = self.prompt_editor.read(cx).text(cx);
2774            cx.notify();
2775        }
2776    }
2777
2778    fn semantic_index_changed(
2779        &mut self,
2780        semantic_index: Model<SemanticIndex>,
2781        cx: &mut ViewContext<Self>,
2782    ) {
2783        let Some(project) = self.project.upgrade() else {
2784            return;
2785        };
2786
2787        let status = semantic_index.read(cx).status(&project);
2788        match status {
2789            SemanticIndexStatus::Indexing {
2790                rate_limit_expiry: Some(_),
2791                ..
2792            } => {
2793                if self.maintain_rate_limit.is_none() {
2794                    self.maintain_rate_limit = Some(cx.spawn(|this, mut cx| async move {
2795                        loop {
2796                            cx.background_executor().timer(Duration::from_secs(1)).await;
2797                            this.update(&mut cx, |_, cx| cx.notify()).log_err();
2798                        }
2799                    }));
2800                }
2801                return;
2802            }
2803            _ => {
2804                self.maintain_rate_limit = None;
2805            }
2806        }
2807    }
2808
2809    fn handle_codegen_changed(&mut self, _: Model<Codegen>, cx: &mut ViewContext<Self>) {
2810        let is_read_only = !self.codegen.read(cx).idle();
2811        self.prompt_editor.update(cx, |editor, _cx| {
2812            let was_read_only = editor.read_only();
2813            if was_read_only != is_read_only {
2814                if is_read_only {
2815                    editor.set_read_only(true);
2816                } else {
2817                    self.confirmed = false;
2818                    editor.set_read_only(false);
2819                }
2820            }
2821        });
2822        cx.notify();
2823    }
2824
2825    fn cancel(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
2826        cx.emit(InlineAssistantEvent::Canceled);
2827    }
2828
2829    fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
2830        if self.confirmed {
2831            cx.emit(InlineAssistantEvent::Dismissed);
2832        } else {
2833            report_assistant_event(self.workspace.clone(), None, AssistantKind::Inline, cx);
2834
2835            let prompt = self.prompt_editor.read(cx).text(cx);
2836            self.prompt_editor
2837                .update(cx, |editor, _cx| editor.set_read_only(true));
2838            cx.emit(InlineAssistantEvent::Confirmed {
2839                prompt,
2840                include_conversation: self.include_conversation,
2841                retrieve_context: self.retrieve_context,
2842            });
2843            self.confirmed = true;
2844            cx.notify();
2845        }
2846    }
2847
2848    fn toggle_retrieve_context(&mut self, _: &ToggleRetrieveContext, cx: &mut ViewContext<Self>) {
2849        let semantic_permissioned = self.semantic_permissioned(cx);
2850
2851        let Some(project) = self.project.upgrade() else {
2852            return;
2853        };
2854
2855        let project_name = project
2856            .read(cx)
2857            .worktree_root_names(cx)
2858            .collect::<Vec<&str>>()
2859            .join("/");
2860        let is_plural = project_name.chars().filter(|letter| *letter == '/').count() > 0;
2861        let prompt_text = format!("Would you like to index the '{}' project{} for context retrieval? This requires sending code to the OpenAI API", project_name,
2862            if is_plural {
2863                "s"
2864            } else {""});
2865
2866        cx.spawn(|this, mut cx| async move {
2867            // If Necessary prompt user
2868            if !semantic_permissioned.await.unwrap_or(false) {
2869                let answer = this.update(&mut cx, |_, cx| {
2870                    cx.prompt(
2871                        PromptLevel::Info,
2872                        prompt_text.as_str(),
2873                        &["Continue", "Cancel"],
2874                    )
2875                })?;
2876
2877                if answer.await? == 0 {
2878                    this.update(&mut cx, |this, _| {
2879                        this.semantic_permissioned = Some(true);
2880                    })?;
2881                } else {
2882                    return anyhow::Ok(());
2883                }
2884            }
2885
2886            // If permissioned, update context appropriately
2887            this.update(&mut cx, |this, cx| {
2888                this.retrieve_context = !this.retrieve_context;
2889
2890                cx.emit(InlineAssistantEvent::RetrieveContextToggled {
2891                    retrieve_context: this.retrieve_context,
2892                });
2893
2894                if this.retrieve_context {
2895                    this.index_project(cx).log_err();
2896                }
2897
2898                cx.notify();
2899            })?;
2900
2901            anyhow::Ok(())
2902        })
2903        .detach_and_log_err(cx);
2904    }
2905
2906    fn index_project(&self, cx: &mut ViewContext<Self>) -> anyhow::Result<()> {
2907        let Some(project) = self.project.upgrade() else {
2908            return Err(anyhow!("project was dropped!"));
2909        };
2910
2911        let semantic_permissioned = self.semantic_permissioned(cx);
2912        if let Some(semantic_index) = SemanticIndex::global(cx) {
2913            cx.spawn(|_, mut cx| async move {
2914                // This has to be updated to accomodate for semantic_permissions
2915                if semantic_permissioned.await.unwrap_or(false) {
2916                    semantic_index
2917                        .update(&mut cx, |index, cx| index.index_project(project, cx))?
2918                        .await
2919                } else {
2920                    Err(anyhow!("project is not permissioned for semantic indexing"))
2921                }
2922            })
2923            .detach_and_log_err(cx);
2924        }
2925
2926        anyhow::Ok(())
2927    }
2928
2929    fn retrieve_context_status(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
2930        let Some(project) = self.project.upgrade() else {
2931            return None;
2932        };
2933
2934        let semantic_index = SemanticIndex::global(cx)?;
2935        let status = semantic_index.update(cx, |index, _| index.status(&project));
2936        match status {
2937            SemanticIndexStatus::NotAuthenticated {} => Some(
2938                div()
2939                    .id("error")
2940                    .tooltip(|cx| Tooltip::text("Not Authenticated. Please ensure you have a valid 'OPENAI_API_KEY' in your environment variables.", cx))
2941                    .child(IconElement::new(Icon::XCircle))
2942                    .into_any_element()
2943            ),
2944
2945            SemanticIndexStatus::NotIndexed {} => Some(
2946                div()
2947                    .id("error")
2948                    .tooltip(|cx| Tooltip::text("Not Indexed", cx))
2949                    .child(IconElement::new(Icon::XCircle))
2950                    .into_any_element()
2951            ),
2952
2953            SemanticIndexStatus::Indexing {
2954                remaining_files,
2955                rate_limit_expiry,
2956            } => {
2957                let mut status_text = if remaining_files == 0 {
2958                    "Indexing...".to_string()
2959                } else {
2960                    format!("Remaining files to index: {remaining_files}")
2961                };
2962
2963                if let Some(rate_limit_expiry) = rate_limit_expiry {
2964                    let remaining_seconds = rate_limit_expiry.duration_since(Instant::now());
2965                    if remaining_seconds > Duration::from_secs(0) && remaining_files > 0 {
2966                        write!(
2967                            status_text,
2968                            " (rate limit expires in {}s)",
2969                            remaining_seconds.as_secs()
2970                        )
2971                        .unwrap();
2972                    }
2973                }
2974
2975                let status_text = SharedString::from(status_text);
2976                Some(
2977                    div()
2978                        .id("update")
2979                        .tooltip(move |cx| Tooltip::text(status_text.clone(), cx))
2980                        .child(IconElement::new(Icon::Update).color(Color::Info))
2981                        .into_any_element()
2982                )
2983            }
2984
2985            SemanticIndexStatus::Indexed {} => Some(
2986                div()
2987                    .id("check")
2988                    .tooltip(|cx| Tooltip::text("Index up to date", cx))
2989                    .child(IconElement::new(Icon::Check).color(Color::Success))
2990                    .into_any_element()
2991            ),
2992        }
2993    }
2994
2995    fn toggle_include_conversation(
2996        &mut self,
2997        _: &ToggleIncludeConversation,
2998        cx: &mut ViewContext<Self>,
2999    ) {
3000        self.include_conversation = !self.include_conversation;
3001        cx.emit(InlineAssistantEvent::IncludeConversationToggled {
3002            include_conversation: self.include_conversation,
3003        });
3004        cx.notify();
3005    }
3006
3007    fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
3008        if let Some(ix) = self.prompt_history_ix {
3009            if ix > 0 {
3010                self.prompt_history_ix = Some(ix - 1);
3011                let prompt = self.prompt_history[ix - 1].clone();
3012                self.set_prompt(&prompt, cx);
3013            }
3014        } else if !self.prompt_history.is_empty() {
3015            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
3016            let prompt = self.prompt_history[self.prompt_history.len() - 1].clone();
3017            self.set_prompt(&prompt, cx);
3018        }
3019    }
3020
3021    fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
3022        if let Some(ix) = self.prompt_history_ix {
3023            if ix < self.prompt_history.len() - 1 {
3024                self.prompt_history_ix = Some(ix + 1);
3025                let prompt = self.prompt_history[ix + 1].clone();
3026                self.set_prompt(&prompt, cx);
3027            } else {
3028                self.prompt_history_ix = None;
3029                let pending_prompt = self.pending_prompt.clone();
3030                self.set_prompt(&pending_prompt, cx);
3031            }
3032        }
3033    }
3034
3035    fn set_prompt(&mut self, prompt: &str, cx: &mut ViewContext<Self>) {
3036        self.prompt_editor.update(cx, |editor, cx| {
3037            editor.buffer().update(cx, |buffer, cx| {
3038                let len = buffer.len(cx);
3039                buffer.edit([(0..len, prompt)], None, cx);
3040            });
3041        });
3042    }
3043
3044    fn render_prompt_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3045        let settings = ThemeSettings::get_global(cx);
3046        let text_style = TextStyle {
3047            color: if self.prompt_editor.read(cx).read_only() {
3048                cx.theme().colors().text_disabled
3049            } else {
3050                cx.theme().colors().text
3051            },
3052            font_family: settings.ui_font.family.clone(),
3053            font_features: settings.ui_font.features,
3054            font_size: rems(0.875).into(),
3055            font_weight: FontWeight::NORMAL,
3056            font_style: FontStyle::Normal,
3057            line_height: relative(1.).into(),
3058            background_color: None,
3059            underline: None,
3060            white_space: WhiteSpace::Normal,
3061        };
3062        EditorElement::new(
3063            &self.prompt_editor,
3064            EditorStyle {
3065                background: cx.theme().colors().editor_background,
3066                local_player: cx.theme().players().local(),
3067                text: text_style,
3068                ..Default::default()
3069            },
3070        )
3071    }
3072}
3073
3074// This wouldn't need to exist if we could pass parameters when rendering child views.
3075#[derive(Copy, Clone, Default)]
3076struct BlockMeasurements {
3077    anchor_x: Pixels,
3078    gutter_width: Pixels,
3079}
3080
3081struct PendingInlineAssist {
3082    editor: WeakView<Editor>,
3083    inline_assistant: Option<(BlockId, View<InlineAssistant>)>,
3084    codegen: Model<Codegen>,
3085    _subscriptions: Vec<Subscription>,
3086    project: WeakModel<Project>,
3087}
3088
3089fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3090    ranges.sort_unstable_by(|a, b| {
3091        a.start
3092            .cmp(&b.start, buffer)
3093            .then_with(|| b.end.cmp(&a.end, buffer))
3094    });
3095
3096    let mut ix = 0;
3097    while ix + 1 < ranges.len() {
3098        let b = ranges[ix + 1].clone();
3099        let a = &mut ranges[ix];
3100        if a.end.cmp(&b.start, buffer).is_gt() {
3101            if a.end.cmp(&b.end, buffer).is_lt() {
3102                a.end = b.end;
3103            }
3104            ranges.remove(ix + 1);
3105        } else {
3106            ix += 1;
3107        }
3108    }
3109}
3110
3111#[cfg(test)]
3112mod tests {
3113    use super::*;
3114    use crate::MessageId;
3115    use ai::test::FakeCompletionProvider;
3116    use gpui::AppContext;
3117
3118    #[gpui::test]
3119    fn test_inserting_and_removing_messages(cx: &mut AppContext) {
3120        let settings_store = SettingsStore::test(cx);
3121        cx.set_global(settings_store);
3122        init(cx);
3123        let registry = Arc::new(LanguageRegistry::test());
3124
3125        let completion_provider = Arc::new(FakeCompletionProvider::new());
3126        let conversation =
3127            cx.build_model(|cx| Conversation::new(registry, cx, completion_provider));
3128        let buffer = conversation.read(cx).buffer.clone();
3129
3130        let message_1 = conversation.read(cx).message_anchors[0].clone();
3131        assert_eq!(
3132            messages(&conversation, cx),
3133            vec![(message_1.id, Role::User, 0..0)]
3134        );
3135
3136        let message_2 = conversation.update(cx, |conversation, cx| {
3137            conversation
3138                .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx)
3139                .unwrap()
3140        });
3141        assert_eq!(
3142            messages(&conversation, cx),
3143            vec![
3144                (message_1.id, Role::User, 0..1),
3145                (message_2.id, Role::Assistant, 1..1)
3146            ]
3147        );
3148
3149        buffer.update(cx, |buffer, cx| {
3150            buffer.edit([(0..0, "1"), (1..1, "2")], None, cx)
3151        });
3152        assert_eq!(
3153            messages(&conversation, cx),
3154            vec![
3155                (message_1.id, Role::User, 0..2),
3156                (message_2.id, Role::Assistant, 2..3)
3157            ]
3158        );
3159
3160        let message_3 = conversation.update(cx, |conversation, cx| {
3161            conversation
3162                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3163                .unwrap()
3164        });
3165        assert_eq!(
3166            messages(&conversation, cx),
3167            vec![
3168                (message_1.id, Role::User, 0..2),
3169                (message_2.id, Role::Assistant, 2..4),
3170                (message_3.id, Role::User, 4..4)
3171            ]
3172        );
3173
3174        let message_4 = conversation.update(cx, |conversation, cx| {
3175            conversation
3176                .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3177                .unwrap()
3178        });
3179        assert_eq!(
3180            messages(&conversation, cx),
3181            vec![
3182                (message_1.id, Role::User, 0..2),
3183                (message_2.id, Role::Assistant, 2..4),
3184                (message_4.id, Role::User, 4..5),
3185                (message_3.id, Role::User, 5..5),
3186            ]
3187        );
3188
3189        buffer.update(cx, |buffer, cx| {
3190            buffer.edit([(4..4, "C"), (5..5, "D")], None, cx)
3191        });
3192        assert_eq!(
3193            messages(&conversation, cx),
3194            vec![
3195                (message_1.id, Role::User, 0..2),
3196                (message_2.id, Role::Assistant, 2..4),
3197                (message_4.id, Role::User, 4..6),
3198                (message_3.id, Role::User, 6..7),
3199            ]
3200        );
3201
3202        // Deleting across message boundaries merges the messages.
3203        buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx));
3204        assert_eq!(
3205            messages(&conversation, cx),
3206            vec![
3207                (message_1.id, Role::User, 0..3),
3208                (message_3.id, Role::User, 3..4),
3209            ]
3210        );
3211
3212        // Undoing the deletion should also undo the merge.
3213        buffer.update(cx, |buffer, cx| buffer.undo(cx));
3214        assert_eq!(
3215            messages(&conversation, cx),
3216            vec![
3217                (message_1.id, Role::User, 0..2),
3218                (message_2.id, Role::Assistant, 2..4),
3219                (message_4.id, Role::User, 4..6),
3220                (message_3.id, Role::User, 6..7),
3221            ]
3222        );
3223
3224        // Redoing the deletion should also redo the merge.
3225        buffer.update(cx, |buffer, cx| buffer.redo(cx));
3226        assert_eq!(
3227            messages(&conversation, cx),
3228            vec![
3229                (message_1.id, Role::User, 0..3),
3230                (message_3.id, Role::User, 3..4),
3231            ]
3232        );
3233
3234        // Ensure we can still insert after a merged message.
3235        let message_5 = conversation.update(cx, |conversation, cx| {
3236            conversation
3237                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3238                .unwrap()
3239        });
3240        assert_eq!(
3241            messages(&conversation, cx),
3242            vec![
3243                (message_1.id, Role::User, 0..3),
3244                (message_5.id, Role::System, 3..4),
3245                (message_3.id, Role::User, 4..5)
3246            ]
3247        );
3248    }
3249
3250    #[gpui::test]
3251    fn test_message_splitting(cx: &mut AppContext) {
3252        let settings_store = SettingsStore::test(cx);
3253        cx.set_global(settings_store);
3254        init(cx);
3255        let registry = Arc::new(LanguageRegistry::test());
3256        let completion_provider = Arc::new(FakeCompletionProvider::new());
3257
3258        let conversation =
3259            cx.build_model(|cx| Conversation::new(registry, cx, completion_provider));
3260        let buffer = conversation.read(cx).buffer.clone();
3261
3262        let message_1 = conversation.read(cx).message_anchors[0].clone();
3263        assert_eq!(
3264            messages(&conversation, cx),
3265            vec![(message_1.id, Role::User, 0..0)]
3266        );
3267
3268        buffer.update(cx, |buffer, cx| {
3269            buffer.edit([(0..0, "aaa\nbbb\nccc\nddd\n")], None, cx)
3270        });
3271
3272        let (_, message_2) =
3273            conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx));
3274        let message_2 = message_2.unwrap();
3275
3276        // We recycle newlines in the middle of a split message
3277        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n");
3278        assert_eq!(
3279            messages(&conversation, cx),
3280            vec![
3281                (message_1.id, Role::User, 0..4),
3282                (message_2.id, Role::User, 4..16),
3283            ]
3284        );
3285
3286        let (_, message_3) =
3287            conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx));
3288        let message_3 = message_3.unwrap();
3289
3290        // We don't recycle newlines at the end of a split message
3291        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
3292        assert_eq!(
3293            messages(&conversation, cx),
3294            vec![
3295                (message_1.id, Role::User, 0..4),
3296                (message_3.id, Role::User, 4..5),
3297                (message_2.id, Role::User, 5..17),
3298            ]
3299        );
3300
3301        let (_, message_4) =
3302            conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx));
3303        let message_4 = message_4.unwrap();
3304        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
3305        assert_eq!(
3306            messages(&conversation, cx),
3307            vec![
3308                (message_1.id, Role::User, 0..4),
3309                (message_3.id, Role::User, 4..5),
3310                (message_2.id, Role::User, 5..9),
3311                (message_4.id, Role::User, 9..17),
3312            ]
3313        );
3314
3315        let (_, message_5) =
3316            conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx));
3317        let message_5 = message_5.unwrap();
3318        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n");
3319        assert_eq!(
3320            messages(&conversation, cx),
3321            vec![
3322                (message_1.id, Role::User, 0..4),
3323                (message_3.id, Role::User, 4..5),
3324                (message_2.id, Role::User, 5..9),
3325                (message_4.id, Role::User, 9..10),
3326                (message_5.id, Role::User, 10..18),
3327            ]
3328        );
3329
3330        let (message_6, message_7) = conversation.update(cx, |conversation, cx| {
3331            conversation.split_message(14..16, cx)
3332        });
3333        let message_6 = message_6.unwrap();
3334        let message_7 = message_7.unwrap();
3335        assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n");
3336        assert_eq!(
3337            messages(&conversation, cx),
3338            vec![
3339                (message_1.id, Role::User, 0..4),
3340                (message_3.id, Role::User, 4..5),
3341                (message_2.id, Role::User, 5..9),
3342                (message_4.id, Role::User, 9..10),
3343                (message_5.id, Role::User, 10..14),
3344                (message_6.id, Role::User, 14..17),
3345                (message_7.id, Role::User, 17..19),
3346            ]
3347        );
3348    }
3349
3350    #[gpui::test]
3351    fn test_messages_for_offsets(cx: &mut AppContext) {
3352        let settings_store = SettingsStore::test(cx);
3353        cx.set_global(settings_store);
3354        init(cx);
3355        let registry = Arc::new(LanguageRegistry::test());
3356        let completion_provider = Arc::new(FakeCompletionProvider::new());
3357        let conversation =
3358            cx.build_model(|cx| Conversation::new(registry, cx, completion_provider));
3359        let buffer = conversation.read(cx).buffer.clone();
3360
3361        let message_1 = conversation.read(cx).message_anchors[0].clone();
3362        assert_eq!(
3363            messages(&conversation, cx),
3364            vec![(message_1.id, Role::User, 0..0)]
3365        );
3366
3367        buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx));
3368        let message_2 = conversation
3369            .update(cx, |conversation, cx| {
3370                conversation.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx)
3371            })
3372            .unwrap();
3373        buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx));
3374
3375        let message_3 = conversation
3376            .update(cx, |conversation, cx| {
3377                conversation.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3378            })
3379            .unwrap();
3380        buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx));
3381
3382        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc");
3383        assert_eq!(
3384            messages(&conversation, cx),
3385            vec![
3386                (message_1.id, Role::User, 0..4),
3387                (message_2.id, Role::User, 4..8),
3388                (message_3.id, Role::User, 8..11)
3389            ]
3390        );
3391
3392        assert_eq!(
3393            message_ids_for_offsets(&conversation, &[0, 4, 9], cx),
3394            [message_1.id, message_2.id, message_3.id]
3395        );
3396        assert_eq!(
3397            message_ids_for_offsets(&conversation, &[0, 1, 11], cx),
3398            [message_1.id, message_3.id]
3399        );
3400
3401        let message_4 = conversation
3402            .update(cx, |conversation, cx| {
3403                conversation.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx)
3404            })
3405            .unwrap();
3406        assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n");
3407        assert_eq!(
3408            messages(&conversation, cx),
3409            vec![
3410                (message_1.id, Role::User, 0..4),
3411                (message_2.id, Role::User, 4..8),
3412                (message_3.id, Role::User, 8..12),
3413                (message_4.id, Role::User, 12..12)
3414            ]
3415        );
3416        assert_eq!(
3417            message_ids_for_offsets(&conversation, &[0, 4, 8, 12], cx),
3418            [message_1.id, message_2.id, message_3.id, message_4.id]
3419        );
3420
3421        fn message_ids_for_offsets(
3422            conversation: &Model<Conversation>,
3423            offsets: &[usize],
3424            cx: &AppContext,
3425        ) -> Vec<MessageId> {
3426            conversation
3427                .read(cx)
3428                .messages_for_offsets(offsets.iter().copied(), cx)
3429                .into_iter()
3430                .map(|message| message.id)
3431                .collect()
3432        }
3433    }
3434
3435    #[gpui::test]
3436    fn test_serialization(cx: &mut AppContext) {
3437        let settings_store = SettingsStore::test(cx);
3438        cx.set_global(settings_store);
3439        init(cx);
3440        let registry = Arc::new(LanguageRegistry::test());
3441        let completion_provider = Arc::new(FakeCompletionProvider::new());
3442        let conversation =
3443            cx.build_model(|cx| Conversation::new(registry.clone(), cx, completion_provider));
3444        let buffer = conversation.read(cx).buffer.clone();
3445        let message_0 = conversation.read(cx).message_anchors[0].id;
3446        let message_1 = conversation.update(cx, |conversation, cx| {
3447            conversation
3448                .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx)
3449                .unwrap()
3450        });
3451        let message_2 = conversation.update(cx, |conversation, cx| {
3452            conversation
3453                .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3454                .unwrap()
3455        });
3456        buffer.update(cx, |buffer, cx| {
3457            buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx);
3458            buffer.finalize_last_transaction();
3459        });
3460        let _message_3 = conversation.update(cx, |conversation, cx| {
3461            conversation
3462                .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx)
3463                .unwrap()
3464        });
3465        buffer.update(cx, |buffer, cx| buffer.undo(cx));
3466        assert_eq!(buffer.read(cx).text(), "a\nb\nc\n");
3467        assert_eq!(
3468            messages(&conversation, cx),
3469            [
3470                (message_0, Role::User, 0..2),
3471                (message_1.id, Role::Assistant, 2..6),
3472                (message_2.id, Role::System, 6..6),
3473            ]
3474        );
3475
3476        let deserialized_conversation = cx.build_model(|cx| {
3477            Conversation::deserialize(
3478                conversation.read(cx).serialize(cx),
3479                Default::default(),
3480                registry.clone(),
3481                cx,
3482            )
3483        });
3484        let deserialized_buffer = deserialized_conversation.read(cx).buffer.clone();
3485        assert_eq!(deserialized_buffer.read(cx).text(), "a\nb\nc\n");
3486        assert_eq!(
3487            messages(&deserialized_conversation, cx),
3488            [
3489                (message_0, Role::User, 0..2),
3490                (message_1.id, Role::Assistant, 2..6),
3491                (message_2.id, Role::System, 6..6),
3492            ]
3493        );
3494    }
3495
3496    fn messages(
3497        conversation: &Model<Conversation>,
3498        cx: &AppContext,
3499    ) -> Vec<(MessageId, Role, Range<usize>)> {
3500        conversation
3501            .read(cx)
3502            .messages(cx)
3503            .map(|message| (message.id, message.role, message.offset_range))
3504            .collect()
3505    }
3506}
3507
3508fn report_assistant_event(
3509    workspace: WeakView<Workspace>,
3510    conversation_id: Option<String>,
3511    assistant_kind: AssistantKind,
3512    cx: &AppContext,
3513) {
3514    let Some(workspace) = workspace.upgrade() else {
3515        return;
3516    };
3517
3518    let client = workspace.read(cx).project().read(cx).client();
3519    let telemetry = client.telemetry();
3520
3521    let model = AssistantSettings::get_global(cx)
3522        .default_open_ai_model
3523        .clone();
3524
3525    let telemetry_settings = TelemetrySettings::get_global(cx).clone();
3526
3527    telemetry.report_assistant_event(
3528        telemetry_settings,
3529        conversation_id,
3530        assistant_kind,
3531        model.full_name(),
3532    )
3533}