assistant_panel.rs

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