assistant_panel.rs

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