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