assistant_panel.rs

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