assistant_panel.rs

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