assistant_panel.rs

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