assistant_panel.rs

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