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