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