assistant_panel.rs

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