context_editor.rs

   1use anyhow::Result;
   2use assistant_settings::AssistantSettings;
   3use assistant_slash_command::{SlashCommand, SlashCommandOutputSection, SlashCommandWorkingSet};
   4use assistant_slash_commands::{
   5    DefaultSlashCommand, DocsSlashCommand, DocsSlashCommandArgs, FileSlashCommand,
   6    selections_creases,
   7};
   8use client::{proto, zed_urls};
   9use collections::{BTreeSet, HashMap, HashSet, hash_map};
  10use editor::{
  11    Anchor, Editor, EditorEvent, MenuInlineCompletionsPolicy, ProposedChangeLocation,
  12    ProposedChangesEditor, RowExt, ToOffset as _, ToPoint,
  13    actions::{FoldAt, MoveToEndOfLine, Newline, ShowCompletions, UnfoldAt},
  14    display_map::{
  15        BlockContext, BlockId, BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata,
  16        CustomBlockId, FoldId, RenderBlock, ToDisplayPoint,
  17    },
  18    scroll::Autoscroll,
  19};
  20use editor::{FoldPlaceholder, display_map::CreaseId};
  21use fs::Fs;
  22use futures::FutureExt;
  23use gpui::{
  24    Animation, AnimationExt, AnyElement, AnyView, App, AsyncWindowContext, ClipboardEntry,
  25    ClipboardItem, CursorStyle, Empty, Entity, EventEmitter, FocusHandle, Focusable, FontWeight,
  26    Global, InteractiveElement, IntoElement, ParentElement, Pixels, Render, RenderImage,
  27    SharedString, Size, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
  28    WeakEntity, actions, div, img, impl_internal_actions, percentage, point, prelude::*,
  29    pulsating_between, size,
  30};
  31use indexed_docs::IndexedDocsStore;
  32use language::{
  33    BufferSnapshot, LspAdapterDelegate, ToOffset,
  34    language_settings::{SoftWrap, all_language_settings},
  35};
  36use language_model::{
  37    LanguageModelImage, LanguageModelProvider, LanguageModelProviderTosView, LanguageModelRegistry,
  38    Role,
  39};
  40use language_model_selector::{
  41    LanguageModelSelector, LanguageModelSelectorPopoverMenu, ToggleModelSelector,
  42};
  43use multi_buffer::MultiBufferRow;
  44use picker::Picker;
  45use project::lsp_store::LocalLspAdapterDelegate;
  46use project::{Project, Worktree};
  47use rope::Point;
  48use serde::{Deserialize, Serialize};
  49use settings::{Settings, SettingsStore, update_settings_file};
  50use std::{any::TypeId, borrow::Cow, cmp, ops::Range, path::PathBuf, sync::Arc, time::Duration};
  51use text::SelectionGoal;
  52use ui::{
  53    ButtonLike, Disclosure, ElevationIndex, KeyBinding, PopoverMenuHandle, TintColor, Tooltip,
  54    prelude::*,
  55};
  56use util::{ResultExt, maybe};
  57use workspace::searchable::{Direction, SearchableItemHandle};
  58use workspace::{
  59    Save, ShowConfiguration, Toast, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  60    Workspace,
  61    item::{self, FollowableItem, Item, ItemHandle},
  62    notifications::NotificationId,
  63    pane::{self, SaveIntent},
  64    searchable::{SearchEvent, SearchableItem},
  65};
  66
  67use crate::{
  68    AssistantContext, AssistantPatch, AssistantPatchStatus, CacheStatus, Content, ContextEvent,
  69    ContextId, InvokedSlashCommandId, InvokedSlashCommandStatus, Message, MessageId,
  70    MessageMetadata, MessageStatus, ParsedSlashCommand, PendingSlashCommandStatus, RequestType,
  71};
  72use crate::{
  73    ThoughtProcessOutputSection, slash_command::SlashCommandCompletionProvider,
  74    slash_command_picker,
  75};
  76
  77actions!(
  78    assistant,
  79    [
  80        Assist,
  81        ConfirmCommand,
  82        CopyCode,
  83        CycleMessageRole,
  84        Edit,
  85        InsertIntoEditor,
  86        QuoteSelection,
  87        Split,
  88    ]
  89);
  90
  91#[derive(PartialEq, Clone)]
  92pub enum InsertDraggedFiles {
  93    ProjectPaths(Vec<PathBuf>),
  94    ExternalFiles(Vec<PathBuf>),
  95}
  96
  97impl_internal_actions!(assistant, [InsertDraggedFiles]);
  98
  99#[derive(Copy, Clone, Debug, PartialEq)]
 100struct ScrollPosition {
 101    offset_before_cursor: gpui::Point<f32>,
 102    cursor: Anchor,
 103}
 104
 105struct PatchViewState {
 106    crease_id: CreaseId,
 107    editor: Option<PatchEditorState>,
 108    update_task: Option<Task<()>>,
 109}
 110
 111struct PatchEditorState {
 112    editor: WeakEntity<ProposedChangesEditor>,
 113    opened_patch: AssistantPatch,
 114}
 115
 116type MessageHeader = MessageMetadata;
 117
 118#[derive(Clone)]
 119enum AssistError {
 120    FileRequired,
 121    PaymentRequired,
 122    MaxMonthlySpendReached,
 123    Message(SharedString),
 124}
 125
 126pub enum ThoughtProcessStatus {
 127    Pending,
 128    Completed,
 129}
 130
 131pub trait AssistantPanelDelegate {
 132    fn active_context_editor(
 133        &self,
 134        workspace: &mut Workspace,
 135        window: &mut Window,
 136        cx: &mut Context<Workspace>,
 137    ) -> Option<Entity<ContextEditor>>;
 138
 139    fn open_saved_context(
 140        &self,
 141        workspace: &mut Workspace,
 142        path: PathBuf,
 143        window: &mut Window,
 144        cx: &mut Context<Workspace>,
 145    ) -> Task<Result<()>>;
 146
 147    fn open_remote_context(
 148        &self,
 149        workspace: &mut Workspace,
 150        context_id: ContextId,
 151        window: &mut Window,
 152        cx: &mut Context<Workspace>,
 153    ) -> Task<Result<Entity<ContextEditor>>>;
 154
 155    fn quote_selection(
 156        &self,
 157        workspace: &mut Workspace,
 158        creases: Vec<(String, String)>,
 159        window: &mut Window,
 160        cx: &mut Context<Workspace>,
 161    );
 162}
 163
 164impl dyn AssistantPanelDelegate {
 165    /// Returns the global [`AssistantPanelDelegate`], if it exists.
 166    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 167        cx.try_global::<GlobalAssistantPanelDelegate>()
 168            .map(|global| global.0.clone())
 169    }
 170
 171    /// Sets the global [`AssistantPanelDelegate`].
 172    pub fn set_global(delegate: Arc<Self>, cx: &mut App) {
 173        cx.set_global(GlobalAssistantPanelDelegate(delegate));
 174    }
 175}
 176
 177struct GlobalAssistantPanelDelegate(Arc<dyn AssistantPanelDelegate>);
 178
 179impl Global for GlobalAssistantPanelDelegate {}
 180
 181pub struct ContextEditor {
 182    context: Entity<AssistantContext>,
 183    fs: Arc<dyn Fs>,
 184    slash_commands: Arc<SlashCommandWorkingSet>,
 185    workspace: WeakEntity<Workspace>,
 186    project: Entity<Project>,
 187    lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
 188    editor: Entity<Editor>,
 189    pending_thought_process: Option<(CreaseId, language::Anchor)>,
 190    blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
 191    image_blocks: HashSet<CustomBlockId>,
 192    scroll_position: Option<ScrollPosition>,
 193    remote_id: Option<workspace::ViewId>,
 194    pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
 195    invoked_slash_command_creases: HashMap<InvokedSlashCommandId, CreaseId>,
 196    _subscriptions: Vec<Subscription>,
 197    patches: HashMap<Range<language::Anchor>, PatchViewState>,
 198    active_patch: Option<Range<language::Anchor>>,
 199    last_error: Option<AssistError>,
 200    show_accept_terms: bool,
 201    pub(crate) slash_menu_handle:
 202        PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
 203    // dragged_file_worktrees is used to keep references to worktrees that were added
 204    // when the user drag/dropped an external file onto the context editor. Since
 205    // the worktree is not part of the project panel, it would be dropped as soon as
 206    // the file is opened. In order to keep the worktree alive for the duration of the
 207    // context editor, we keep a reference here.
 208    dragged_file_worktrees: Vec<Entity<Worktree>>,
 209    language_model_selector: Entity<LanguageModelSelector>,
 210    language_model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
 211}
 212
 213pub const DEFAULT_TAB_TITLE: &str = "New Chat";
 214const MAX_TAB_TITLE_LEN: usize = 16;
 215
 216impl ContextEditor {
 217    pub fn for_context(
 218        context: Entity<AssistantContext>,
 219        fs: Arc<dyn Fs>,
 220        workspace: WeakEntity<Workspace>,
 221        project: Entity<Project>,
 222        lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
 223        window: &mut Window,
 224        cx: &mut Context<Self>,
 225    ) -> Self {
 226        let completion_provider = SlashCommandCompletionProvider::new(
 227            context.read(cx).slash_commands().clone(),
 228            Some(cx.entity().downgrade()),
 229            Some(workspace.clone()),
 230        );
 231
 232        let editor = cx.new(|cx| {
 233            let mut editor =
 234                Editor::for_buffer(context.read(cx).buffer().clone(), None, window, cx);
 235            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
 236            editor.set_show_line_numbers(false, cx);
 237            editor.set_show_scrollbars(false, cx);
 238            editor.set_show_git_diff_gutter(false, cx);
 239            editor.set_show_code_actions(false, cx);
 240            editor.set_show_runnables(false, cx);
 241            editor.set_show_breakpoints(false, cx);
 242            editor.set_show_wrap_guides(false, cx);
 243            editor.set_show_indent_guides(false, cx);
 244            editor.set_completion_provider(Some(Box::new(completion_provider)));
 245            editor.set_menu_inline_completions_policy(MenuInlineCompletionsPolicy::Never);
 246            editor.set_collaboration_hub(Box::new(project.clone()));
 247
 248            let show_edit_predictions = all_language_settings(None, cx)
 249                .edit_predictions
 250                .enabled_in_assistant;
 251
 252            editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 253
 254            editor
 255        });
 256
 257        let _subscriptions = vec![
 258            cx.observe(&context, |_, _, cx| cx.notify()),
 259            cx.subscribe_in(&context, window, Self::handle_context_event),
 260            cx.subscribe_in(&editor, window, Self::handle_editor_event),
 261            cx.subscribe_in(&editor, window, Self::handle_editor_search_event),
 262            cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 263        ];
 264
 265        let slash_command_sections = context.read(cx).slash_command_output_sections().to_vec();
 266        let thought_process_sections = context.read(cx).thought_process_output_sections().to_vec();
 267        let patch_ranges = context.read(cx).patch_ranges().collect::<Vec<_>>();
 268        let slash_commands = context.read(cx).slash_commands().clone();
 269        let mut this = Self {
 270            context,
 271            slash_commands,
 272            editor,
 273            lsp_adapter_delegate,
 274            blocks: Default::default(),
 275            image_blocks: Default::default(),
 276            scroll_position: None,
 277            remote_id: None,
 278            pending_thought_process: None,
 279            fs: fs.clone(),
 280            workspace,
 281            project,
 282            pending_slash_command_creases: HashMap::default(),
 283            invoked_slash_command_creases: HashMap::default(),
 284            _subscriptions,
 285            patches: HashMap::default(),
 286            active_patch: None,
 287            last_error: None,
 288            show_accept_terms: false,
 289            slash_menu_handle: Default::default(),
 290            dragged_file_worktrees: Vec::new(),
 291            language_model_selector: cx.new(|cx| {
 292                LanguageModelSelector::new(
 293                    move |model, cx| {
 294                        update_settings_file::<AssistantSettings>(
 295                            fs.clone(),
 296                            cx,
 297                            move |settings, _| settings.set_model(model.clone()),
 298                        );
 299                    },
 300                    window,
 301                    cx,
 302                )
 303            }),
 304            language_model_selector_menu_handle: PopoverMenuHandle::default(),
 305        };
 306        this.update_message_headers(cx);
 307        this.update_image_blocks(cx);
 308        this.insert_slash_command_output_sections(slash_command_sections, false, window, cx);
 309        this.insert_thought_process_output_sections(
 310            thought_process_sections
 311                .into_iter()
 312                .map(|section| (section, ThoughtProcessStatus::Completed)),
 313            window,
 314            cx,
 315        );
 316        this.patches_updated(&Vec::new(), &patch_ranges, window, cx);
 317        this
 318    }
 319
 320    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 321        self.editor.update(cx, |editor, cx| {
 322            let show_edit_predictions = all_language_settings(None, cx)
 323                .edit_predictions
 324                .enabled_in_assistant;
 325
 326            editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 327        });
 328    }
 329
 330    pub fn context(&self) -> &Entity<AssistantContext> {
 331        &self.context
 332    }
 333
 334    pub fn editor(&self) -> &Entity<Editor> {
 335        &self.editor
 336    }
 337
 338    pub fn insert_default_prompt(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 339        let command_name = DefaultSlashCommand.name();
 340        self.editor.update(cx, |editor, cx| {
 341            editor.insert(&format!("/{command_name}\n\n"), window, cx)
 342        });
 343        let command = self.context.update(cx, |context, cx| {
 344            context.reparse(cx);
 345            context.parsed_slash_commands()[0].clone()
 346        });
 347        self.run_command(
 348            command.source_range,
 349            &command.name,
 350            &command.arguments,
 351            false,
 352            self.workspace.clone(),
 353            window,
 354            cx,
 355        );
 356    }
 357
 358    fn assist(&mut self, _: &Assist, window: &mut Window, cx: &mut Context<Self>) {
 359        self.send_to_model(RequestType::Chat, window, cx);
 360    }
 361
 362    fn edit(&mut self, _: &Edit, window: &mut Window, cx: &mut Context<Self>) {
 363        self.send_to_model(RequestType::SuggestEdits, window, cx);
 364    }
 365
 366    fn focus_active_patch(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 367        if let Some((_range, patch)) = self.active_patch() {
 368            if let Some(editor) = patch
 369                .editor
 370                .as_ref()
 371                .and_then(|state| state.editor.upgrade())
 372            {
 373                editor.focus_handle(cx).focus(window);
 374                return true;
 375            }
 376        }
 377
 378        false
 379    }
 380
 381    fn send_to_model(
 382        &mut self,
 383        request_type: RequestType,
 384        window: &mut Window,
 385        cx: &mut Context<Self>,
 386    ) {
 387        let provider = LanguageModelRegistry::read_global(cx).active_provider();
 388        if provider
 389            .as_ref()
 390            .map_or(false, |provider| provider.must_accept_terms(cx))
 391        {
 392            self.show_accept_terms = true;
 393            cx.notify();
 394            return;
 395        }
 396
 397        if self.focus_active_patch(window, cx) {
 398            return;
 399        }
 400
 401        self.last_error = None;
 402
 403        if request_type == RequestType::SuggestEdits && !self.context.read(cx).contains_files(cx) {
 404            self.last_error = Some(AssistError::FileRequired);
 405            cx.notify();
 406        } else if let Some(user_message) = self
 407            .context
 408            .update(cx, |context, cx| context.assist(request_type, cx))
 409        {
 410            let new_selection = {
 411                let cursor = user_message
 412                    .start
 413                    .to_offset(self.context.read(cx).buffer().read(cx));
 414                cursor..cursor
 415            };
 416            self.editor.update(cx, |editor, cx| {
 417                editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 418                    selections.select_ranges([new_selection])
 419                });
 420            });
 421            // Avoid scrolling to the new cursor position so the assistant's output is stable.
 422            cx.defer_in(window, |this, _, _| this.scroll_position = None);
 423        }
 424
 425        cx.notify();
 426    }
 427
 428    fn cancel(
 429        &mut self,
 430        _: &editor::actions::Cancel,
 431        _window: &mut Window,
 432        cx: &mut Context<Self>,
 433    ) {
 434        self.last_error = None;
 435
 436        if self
 437            .context
 438            .update(cx, |context, cx| context.cancel_last_assist(cx))
 439        {
 440            return;
 441        }
 442
 443        cx.propagate();
 444    }
 445
 446    fn cycle_message_role(
 447        &mut self,
 448        _: &CycleMessageRole,
 449        _window: &mut Window,
 450        cx: &mut Context<Self>,
 451    ) {
 452        let cursors = self.cursors(cx);
 453        self.context.update(cx, |context, cx| {
 454            let messages = context
 455                .messages_for_offsets(cursors, cx)
 456                .into_iter()
 457                .map(|message| message.id)
 458                .collect();
 459            context.cycle_message_roles(messages, cx)
 460        });
 461    }
 462
 463    fn cursors(&self, cx: &mut App) -> Vec<usize> {
 464        let selections = self
 465            .editor
 466            .update(cx, |editor, cx| editor.selections.all::<usize>(cx));
 467        selections
 468            .into_iter()
 469            .map(|selection| selection.head())
 470            .collect()
 471    }
 472
 473    pub fn insert_command(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
 474        if let Some(command) = self.slash_commands.command(name, cx) {
 475            self.editor.update(cx, |editor, cx| {
 476                editor.transact(window, cx, |editor, window, cx| {
 477                    editor
 478                        .change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel());
 479                    let snapshot = editor.buffer().read(cx).snapshot(cx);
 480                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
 481                    if newest_cursor.column > 0
 482                        || snapshot
 483                            .chars_at(newest_cursor)
 484                            .next()
 485                            .map_or(false, |ch| ch != '\n')
 486                    {
 487                        editor.move_to_end_of_line(
 488                            &MoveToEndOfLine {
 489                                stop_at_soft_wraps: false,
 490                            },
 491                            window,
 492                            cx,
 493                        );
 494                        editor.newline(&Newline, window, cx);
 495                    }
 496
 497                    editor.insert(&format!("/{name}"), window, cx);
 498                    if command.accepts_arguments() {
 499                        editor.insert(" ", window, cx);
 500                        editor.show_completions(&ShowCompletions::default(), window, cx);
 501                    }
 502                });
 503            });
 504            if !command.requires_argument() {
 505                self.confirm_command(&ConfirmCommand, window, cx);
 506            }
 507        }
 508    }
 509
 510    pub fn confirm_command(
 511        &mut self,
 512        _: &ConfirmCommand,
 513        window: &mut Window,
 514        cx: &mut Context<Self>,
 515    ) {
 516        if self.editor.read(cx).has_visible_completions_menu() {
 517            return;
 518        }
 519
 520        let selections = self.editor.read(cx).selections.disjoint_anchors();
 521        let mut commands_by_range = HashMap::default();
 522        let workspace = self.workspace.clone();
 523        self.context.update(cx, |context, cx| {
 524            context.reparse(cx);
 525            for selection in selections.iter() {
 526                if let Some(command) =
 527                    context.pending_command_for_position(selection.head().text_anchor, cx)
 528                {
 529                    commands_by_range
 530                        .entry(command.source_range.clone())
 531                        .or_insert_with(|| command.clone());
 532                }
 533            }
 534        });
 535
 536        if commands_by_range.is_empty() {
 537            cx.propagate();
 538        } else {
 539            for command in commands_by_range.into_values() {
 540                self.run_command(
 541                    command.source_range,
 542                    &command.name,
 543                    &command.arguments,
 544                    true,
 545                    workspace.clone(),
 546                    window,
 547                    cx,
 548                );
 549            }
 550            cx.stop_propagation();
 551        }
 552    }
 553
 554    pub fn run_command(
 555        &mut self,
 556        command_range: Range<language::Anchor>,
 557        name: &str,
 558        arguments: &[String],
 559        ensure_trailing_newline: bool,
 560        workspace: WeakEntity<Workspace>,
 561        window: &mut Window,
 562        cx: &mut Context<Self>,
 563    ) {
 564        if let Some(command) = self.slash_commands.command(name, cx) {
 565            let context = self.context.read(cx);
 566            let sections = context
 567                .slash_command_output_sections()
 568                .into_iter()
 569                .filter(|section| section.is_valid(context.buffer().read(cx)))
 570                .cloned()
 571                .collect::<Vec<_>>();
 572            let snapshot = context.buffer().read(cx).snapshot();
 573            let output = command.run(
 574                arguments,
 575                &sections,
 576                snapshot,
 577                workspace,
 578                self.lsp_adapter_delegate.clone(),
 579                window,
 580                cx,
 581            );
 582            self.context.update(cx, |context, cx| {
 583                context.insert_command_output(
 584                    command_range,
 585                    name,
 586                    output,
 587                    ensure_trailing_newline,
 588                    cx,
 589                )
 590            });
 591        }
 592    }
 593
 594    fn handle_context_event(
 595        &mut self,
 596        _: &Entity<AssistantContext>,
 597        event: &ContextEvent,
 598        window: &mut Window,
 599        cx: &mut Context<Self>,
 600    ) {
 601        let context_editor = cx.entity().downgrade();
 602
 603        match event {
 604            ContextEvent::MessagesEdited => {
 605                self.update_message_headers(cx);
 606                self.update_image_blocks(cx);
 607                self.context.update(cx, |context, cx| {
 608                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
 609                });
 610            }
 611            ContextEvent::SummaryChanged => {
 612                cx.emit(EditorEvent::TitleChanged);
 613                self.context.update(cx, |context, cx| {
 614                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
 615                });
 616            }
 617            ContextEvent::StartedThoughtProcess(range) => {
 618                let creases = self.insert_thought_process_output_sections(
 619                    [(
 620                        ThoughtProcessOutputSection {
 621                            range: range.clone(),
 622                        },
 623                        ThoughtProcessStatus::Pending,
 624                    )],
 625                    window,
 626                    cx,
 627                );
 628                self.pending_thought_process = Some((creases[0], range.start));
 629            }
 630            ContextEvent::EndedThoughtProcess(end) => {
 631                if let Some((crease_id, start)) = self.pending_thought_process.take() {
 632                    self.editor.update(cx, |editor, cx| {
 633                        let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
 634                        let (excerpt_id, _, _) = multi_buffer_snapshot.as_singleton().unwrap();
 635                        let start_anchor = multi_buffer_snapshot
 636                            .anchor_in_excerpt(*excerpt_id, start)
 637                            .unwrap();
 638
 639                        editor.display_map.update(cx, |display_map, cx| {
 640                            display_map.unfold_intersecting(
 641                                vec![start_anchor..start_anchor],
 642                                true,
 643                                cx,
 644                            );
 645                        });
 646                        editor.remove_creases(vec![crease_id], cx);
 647                    });
 648                    self.insert_thought_process_output_sections(
 649                        [(
 650                            ThoughtProcessOutputSection { range: start..*end },
 651                            ThoughtProcessStatus::Completed,
 652                        )],
 653                        window,
 654                        cx,
 655                    );
 656                }
 657            }
 658            ContextEvent::StreamedCompletion => {
 659                self.editor.update(cx, |editor, cx| {
 660                    if let Some(scroll_position) = self.scroll_position {
 661                        let snapshot = editor.snapshot(window, cx);
 662                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
 663                        let scroll_top =
 664                            cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
 665                        editor.set_scroll_position(
 666                            point(scroll_position.offset_before_cursor.x, scroll_top),
 667                            window,
 668                            cx,
 669                        );
 670                    }
 671                });
 672            }
 673            ContextEvent::PatchesUpdated { removed, updated } => {
 674                self.patches_updated(removed, updated, window, cx);
 675            }
 676            ContextEvent::ParsedSlashCommandsUpdated { removed, updated } => {
 677                self.editor.update(cx, |editor, cx| {
 678                    let buffer = editor.buffer().read(cx).snapshot(cx);
 679                    let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
 680
 681                    editor.remove_creases(
 682                        removed
 683                            .iter()
 684                            .filter_map(|range| self.pending_slash_command_creases.remove(range)),
 685                        cx,
 686                    );
 687
 688                    let crease_ids = editor.insert_creases(
 689                        updated.iter().map(|command| {
 690                            let workspace = self.workspace.clone();
 691                            let confirm_command = Arc::new({
 692                                let context_editor = context_editor.clone();
 693                                let command = command.clone();
 694                                move |window: &mut Window, cx: &mut App| {
 695                                    context_editor
 696                                        .update(cx, |context_editor, cx| {
 697                                            context_editor.run_command(
 698                                                command.source_range.clone(),
 699                                                &command.name,
 700                                                &command.arguments,
 701                                                false,
 702                                                workspace.clone(),
 703                                                window,
 704                                                cx,
 705                                            );
 706                                        })
 707                                        .ok();
 708                                }
 709                            });
 710                            let placeholder = FoldPlaceholder {
 711                                render: Arc::new(move |_, _, _| Empty.into_any()),
 712                                ..Default::default()
 713                            };
 714                            let render_toggle = {
 715                                let confirm_command = confirm_command.clone();
 716                                let command = command.clone();
 717                                move |row, _, _, _window: &mut Window, _cx: &mut App| {
 718                                    render_pending_slash_command_gutter_decoration(
 719                                        row,
 720                                        &command.status,
 721                                        confirm_command.clone(),
 722                                    )
 723                                }
 724                            };
 725                            let render_trailer = {
 726                                let command = command.clone();
 727                                move |row, _unfold, _window: &mut Window, cx: &mut App| {
 728                                    // TODO: In the future we should investigate how we can expose
 729                                    // this as a hook on the `SlashCommand` trait so that we don't
 730                                    // need to special-case it here.
 731                                    if command.name == DocsSlashCommand::NAME {
 732                                        return render_docs_slash_command_trailer(
 733                                            row,
 734                                            command.clone(),
 735                                            cx,
 736                                        );
 737                                    }
 738
 739                                    Empty.into_any()
 740                                }
 741                            };
 742
 743                            let start = buffer
 744                                .anchor_in_excerpt(excerpt_id, command.source_range.start)
 745                                .unwrap();
 746                            let end = buffer
 747                                .anchor_in_excerpt(excerpt_id, command.source_range.end)
 748                                .unwrap();
 749                            Crease::inline(start..end, placeholder, render_toggle, render_trailer)
 750                        }),
 751                        cx,
 752                    );
 753
 754                    self.pending_slash_command_creases.extend(
 755                        updated
 756                            .iter()
 757                            .map(|command| command.source_range.clone())
 758                            .zip(crease_ids),
 759                    );
 760                })
 761            }
 762            ContextEvent::InvokedSlashCommandChanged { command_id } => {
 763                self.update_invoked_slash_command(*command_id, window, cx);
 764            }
 765            ContextEvent::SlashCommandOutputSectionAdded { section } => {
 766                self.insert_slash_command_output_sections([section.clone()], false, window, cx);
 767            }
 768            ContextEvent::Operation(_) => {}
 769            ContextEvent::ShowAssistError(error_message) => {
 770                self.last_error = Some(AssistError::Message(error_message.clone()));
 771            }
 772            ContextEvent::ShowPaymentRequiredError => {
 773                self.last_error = Some(AssistError::PaymentRequired);
 774            }
 775            ContextEvent::ShowMaxMonthlySpendReachedError => {
 776                self.last_error = Some(AssistError::MaxMonthlySpendReached);
 777            }
 778        }
 779    }
 780
 781    fn update_invoked_slash_command(
 782        &mut self,
 783        command_id: InvokedSlashCommandId,
 784        window: &mut Window,
 785        cx: &mut Context<Self>,
 786    ) {
 787        if let Some(invoked_slash_command) =
 788            self.context.read(cx).invoked_slash_command(&command_id)
 789        {
 790            if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
 791                let run_commands_in_ranges = invoked_slash_command
 792                    .run_commands_in_ranges
 793                    .iter()
 794                    .cloned()
 795                    .collect::<Vec<_>>();
 796                for range in run_commands_in_ranges {
 797                    let commands = self.context.update(cx, |context, cx| {
 798                        context.reparse(cx);
 799                        context
 800                            .pending_commands_for_range(range.clone(), cx)
 801                            .to_vec()
 802                    });
 803
 804                    for command in commands {
 805                        self.run_command(
 806                            command.source_range,
 807                            &command.name,
 808                            &command.arguments,
 809                            false,
 810                            self.workspace.clone(),
 811                            window,
 812                            cx,
 813                        );
 814                    }
 815                }
 816            }
 817        }
 818
 819        self.editor.update(cx, |editor, cx| {
 820            if let Some(invoked_slash_command) =
 821                self.context.read(cx).invoked_slash_command(&command_id)
 822            {
 823                if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
 824                    let buffer = editor.buffer().read(cx).snapshot(cx);
 825                    let (&excerpt_id, _buffer_id, _buffer_snapshot) =
 826                        buffer.as_singleton().unwrap();
 827
 828                    let start = buffer
 829                        .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.start)
 830                        .unwrap();
 831                    let end = buffer
 832                        .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.end)
 833                        .unwrap();
 834                    editor.remove_folds_with_type(
 835                        &[start..end],
 836                        TypeId::of::<PendingSlashCommand>(),
 837                        false,
 838                        cx,
 839                    );
 840
 841                    editor.remove_creases(
 842                        HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
 843                        cx,
 844                    );
 845                } else if let hash_map::Entry::Vacant(entry) =
 846                    self.invoked_slash_command_creases.entry(command_id)
 847                {
 848                    let buffer = editor.buffer().read(cx).snapshot(cx);
 849                    let (&excerpt_id, _buffer_id, _buffer_snapshot) =
 850                        buffer.as_singleton().unwrap();
 851                    let context = self.context.downgrade();
 852                    let crease_start = buffer
 853                        .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.start)
 854                        .unwrap();
 855                    let crease_end = buffer
 856                        .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.end)
 857                        .unwrap();
 858                    let crease = Crease::inline(
 859                        crease_start..crease_end,
 860                        invoked_slash_command_fold_placeholder(command_id, context),
 861                        fold_toggle("invoked-slash-command"),
 862                        |_row, _folded, _window, _cx| Empty.into_any(),
 863                    );
 864                    let crease_ids = editor.insert_creases([crease.clone()], cx);
 865                    editor.fold_creases(vec![crease], false, window, cx);
 866                    entry.insert(crease_ids[0]);
 867                } else {
 868                    cx.notify()
 869                }
 870            } else {
 871                editor.remove_creases(
 872                    HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
 873                    cx,
 874                );
 875                cx.notify();
 876            };
 877        });
 878    }
 879
 880    fn patches_updated(
 881        &mut self,
 882        removed: &Vec<Range<text::Anchor>>,
 883        updated: &Vec<Range<text::Anchor>>,
 884        window: &mut Window,
 885        cx: &mut Context<ContextEditor>,
 886    ) {
 887        let this = cx.entity().downgrade();
 888        let mut editors_to_close = Vec::new();
 889
 890        self.editor.update(cx, |editor, cx| {
 891            let snapshot = editor.snapshot(window, cx);
 892            let multibuffer = &snapshot.buffer_snapshot;
 893            let (&excerpt_id, _, _) = multibuffer.as_singleton().unwrap();
 894
 895            let mut removed_crease_ids = Vec::new();
 896            let mut ranges_to_unfold: Vec<Range<Anchor>> = Vec::new();
 897            for range in removed {
 898                if let Some(state) = self.patches.remove(range) {
 899                    let patch_start = multibuffer
 900                        .anchor_in_excerpt(excerpt_id, range.start)
 901                        .unwrap();
 902                    let patch_end = multibuffer
 903                        .anchor_in_excerpt(excerpt_id, range.end)
 904                        .unwrap();
 905
 906                    editors_to_close.extend(state.editor.and_then(|state| state.editor.upgrade()));
 907                    ranges_to_unfold.push(patch_start..patch_end);
 908                    removed_crease_ids.push(state.crease_id);
 909                }
 910            }
 911            editor.unfold_ranges(&ranges_to_unfold, true, false, cx);
 912            editor.remove_creases(removed_crease_ids, cx);
 913
 914            for range in updated {
 915                let Some(patch) = self.context.read(cx).patch_for_range(&range, cx).cloned() else {
 916                    continue;
 917                };
 918
 919                let path_count = patch.path_count();
 920                let patch_start = multibuffer
 921                    .anchor_in_excerpt(excerpt_id, patch.range.start)
 922                    .unwrap();
 923                let patch_end = multibuffer
 924                    .anchor_in_excerpt(excerpt_id, patch.range.end)
 925                    .unwrap();
 926                let render_block: RenderBlock = Arc::new({
 927                    let this = this.clone();
 928                    let patch_range = range.clone();
 929                    move |cx: &mut BlockContext| {
 930                        let max_width = cx.max_width;
 931                        let gutter_width = cx.gutter_dimensions.full_width();
 932                        let block_id = cx.block_id;
 933                        let selected = cx.selected;
 934                        let window = &mut cx.window;
 935                        this.update(cx.app, |this, cx| {
 936                            this.render_patch_block(
 937                                patch_range.clone(),
 938                                max_width,
 939                                gutter_width,
 940                                block_id,
 941                                selected,
 942                                window,
 943                                cx,
 944                            )
 945                        })
 946                        .ok()
 947                        .flatten()
 948                        .unwrap_or_else(|| Empty.into_any())
 949                    }
 950                });
 951
 952                let height = path_count as u32 + 1;
 953                let crease = Crease::block(
 954                    patch_start..patch_end,
 955                    height,
 956                    BlockStyle::Flex,
 957                    render_block.clone(),
 958                );
 959
 960                let should_refold;
 961                if let Some(state) = self.patches.get_mut(&range) {
 962                    if let Some(editor_state) = &state.editor {
 963                        if editor_state.opened_patch != patch {
 964                            state.update_task = Some({
 965                                let this = this.clone();
 966                                cx.spawn_in(window, async move |_, cx| {
 967                                    Self::update_patch_editor(this.clone(), patch, cx)
 968                                        .await
 969                                        .log_err();
 970                                })
 971                            });
 972                        }
 973                    }
 974
 975                    should_refold =
 976                        snapshot.intersects_fold(patch_start.to_offset(&snapshot.buffer_snapshot));
 977                } else {
 978                    let crease_id = editor.insert_creases([crease.clone()], cx)[0];
 979                    self.patches.insert(
 980                        range.clone(),
 981                        PatchViewState {
 982                            crease_id,
 983                            editor: None,
 984                            update_task: None,
 985                        },
 986                    );
 987
 988                    should_refold = true;
 989                }
 990
 991                if should_refold {
 992                    editor.unfold_ranges(&[patch_start..patch_end], true, false, cx);
 993                    editor.fold_creases(vec![crease], false, window, cx);
 994                }
 995            }
 996        });
 997
 998        for editor in editors_to_close {
 999            self.close_patch_editor(editor, window, cx);
1000        }
1001
1002        self.update_active_patch(window, cx);
1003    }
1004
1005    fn insert_thought_process_output_sections(
1006        &mut self,
1007        sections: impl IntoIterator<
1008            Item = (
1009                ThoughtProcessOutputSection<language::Anchor>,
1010                ThoughtProcessStatus,
1011            ),
1012        >,
1013        window: &mut Window,
1014        cx: &mut Context<Self>,
1015    ) -> Vec<CreaseId> {
1016        self.editor.update(cx, |editor, cx| {
1017            let buffer = editor.buffer().read(cx).snapshot(cx);
1018            let excerpt_id = *buffer.as_singleton().unwrap().0;
1019            let mut buffer_rows_to_fold = BTreeSet::new();
1020            let mut creases = Vec::new();
1021            for (section, status) in sections {
1022                let start = buffer
1023                    .anchor_in_excerpt(excerpt_id, section.range.start)
1024                    .unwrap();
1025                let end = buffer
1026                    .anchor_in_excerpt(excerpt_id, section.range.end)
1027                    .unwrap();
1028                let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1029                buffer_rows_to_fold.insert(buffer_row);
1030                creases.push(
1031                    Crease::inline(
1032                        start..end,
1033                        FoldPlaceholder {
1034                            render: render_thought_process_fold_icon_button(
1035                                cx.entity().downgrade(),
1036                                status,
1037                            ),
1038                            merge_adjacent: false,
1039                            ..Default::default()
1040                        },
1041                        render_slash_command_output_toggle,
1042                        |_, _, _, _| Empty.into_any_element(),
1043                    )
1044                    .with_metadata(CreaseMetadata {
1045                        icon: IconName::Ai,
1046                        label: "Thinking Process".into(),
1047                    }),
1048                );
1049            }
1050
1051            let creases = editor.insert_creases(creases, cx);
1052
1053            for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1054                editor.fold_at(&FoldAt { buffer_row }, window, cx);
1055            }
1056
1057            creases
1058        })
1059    }
1060
1061    fn insert_slash_command_output_sections(
1062        &mut self,
1063        sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
1064        expand_result: bool,
1065        window: &mut Window,
1066        cx: &mut Context<Self>,
1067    ) {
1068        self.editor.update(cx, |editor, cx| {
1069            let buffer = editor.buffer().read(cx).snapshot(cx);
1070            let excerpt_id = *buffer.as_singleton().unwrap().0;
1071            let mut buffer_rows_to_fold = BTreeSet::new();
1072            let mut creases = Vec::new();
1073            for section in sections {
1074                let start = buffer
1075                    .anchor_in_excerpt(excerpt_id, section.range.start)
1076                    .unwrap();
1077                let end = buffer
1078                    .anchor_in_excerpt(excerpt_id, section.range.end)
1079                    .unwrap();
1080                let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1081                buffer_rows_to_fold.insert(buffer_row);
1082                creases.push(
1083                    Crease::inline(
1084                        start..end,
1085                        FoldPlaceholder {
1086                            render: render_fold_icon_button(
1087                                cx.entity().downgrade(),
1088                                section.icon,
1089                                section.label.clone(),
1090                            ),
1091                            merge_adjacent: false,
1092                            ..Default::default()
1093                        },
1094                        render_slash_command_output_toggle,
1095                        |_, _, _, _| Empty.into_any_element(),
1096                    )
1097                    .with_metadata(CreaseMetadata {
1098                        icon: section.icon,
1099                        label: section.label,
1100                    }),
1101                );
1102            }
1103
1104            editor.insert_creases(creases, cx);
1105
1106            if expand_result {
1107                buffer_rows_to_fold.clear();
1108            }
1109            for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1110                editor.fold_at(&FoldAt { buffer_row }, window, cx);
1111            }
1112        });
1113    }
1114
1115    fn handle_editor_event(
1116        &mut self,
1117        _: &Entity<Editor>,
1118        event: &EditorEvent,
1119        window: &mut Window,
1120        cx: &mut Context<Self>,
1121    ) {
1122        match event {
1123            EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
1124                let cursor_scroll_position = self.cursor_scroll_position(window, cx);
1125                if *autoscroll {
1126                    self.scroll_position = cursor_scroll_position;
1127                } else if self.scroll_position != cursor_scroll_position {
1128                    self.scroll_position = None;
1129                }
1130            }
1131            EditorEvent::SelectionsChanged { .. } => {
1132                self.scroll_position = self.cursor_scroll_position(window, cx);
1133                self.update_active_patch(window, cx);
1134            }
1135            _ => {}
1136        }
1137        cx.emit(event.clone());
1138    }
1139
1140    fn active_patch(&self) -> Option<(Range<text::Anchor>, &PatchViewState)> {
1141        let patch = self.active_patch.as_ref()?;
1142        Some((patch.clone(), self.patches.get(&patch)?))
1143    }
1144
1145    fn update_active_patch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1146        let newest_cursor = self.editor.update(cx, |editor, cx| {
1147            editor.selections.newest::<Point>(cx).head()
1148        });
1149        let context = self.context.read(cx);
1150
1151        let new_patch = context.patch_containing(newest_cursor, cx).cloned();
1152
1153        if new_patch.as_ref().map(|p| &p.range) == self.active_patch.as_ref() {
1154            return;
1155        }
1156
1157        if let Some(old_patch_range) = self.active_patch.take() {
1158            if let Some(patch_state) = self.patches.get_mut(&old_patch_range) {
1159                if let Some(state) = patch_state.editor.take() {
1160                    if let Some(editor) = state.editor.upgrade() {
1161                        self.close_patch_editor(editor, window, cx);
1162                    }
1163                }
1164            }
1165        }
1166
1167        if let Some(new_patch) = new_patch {
1168            self.active_patch = Some(new_patch.range.clone());
1169
1170            if let Some(patch_state) = self.patches.get_mut(&new_patch.range) {
1171                let mut editor = None;
1172                if let Some(state) = &patch_state.editor {
1173                    if let Some(opened_editor) = state.editor.upgrade() {
1174                        editor = Some(opened_editor);
1175                    }
1176                }
1177
1178                if let Some(editor) = editor {
1179                    self.workspace
1180                        .update(cx, |workspace, cx| {
1181                            workspace.activate_item(&editor, true, false, window, cx);
1182                        })
1183                        .ok();
1184                } else {
1185                    patch_state.update_task = Some(cx.spawn_in(window, async move |this, cx| {
1186                        Self::open_patch_editor(this, new_patch, cx).await.log_err();
1187                    }));
1188                }
1189            }
1190        }
1191    }
1192
1193    fn close_patch_editor(
1194        &mut self,
1195        editor: Entity<ProposedChangesEditor>,
1196        window: &mut Window,
1197        cx: &mut Context<ContextEditor>,
1198    ) {
1199        self.workspace
1200            .update(cx, |workspace, cx| {
1201                if let Some(pane) = workspace.pane_for(&editor) {
1202                    pane.update(cx, |pane, cx| {
1203                        let item_id = editor.entity_id();
1204                        if !editor.read(cx).focus_handle(cx).is_focused(window) {
1205                            pane.close_item_by_id(item_id, SaveIntent::Skip, window, cx)
1206                                .detach_and_log_err(cx);
1207                        }
1208                    });
1209                }
1210            })
1211            .ok();
1212    }
1213
1214    async fn open_patch_editor(
1215        this: WeakEntity<Self>,
1216        patch: AssistantPatch,
1217        cx: &mut AsyncWindowContext,
1218    ) -> Result<()> {
1219        let project = this.read_with(cx, |this, _| this.project.clone())?;
1220        let resolved_patch = patch.resolve(project.clone(), cx).await;
1221
1222        let editor = cx.new_window_entity(|window, cx| {
1223            let editor = ProposedChangesEditor::new(
1224                patch.title.clone(),
1225                resolved_patch
1226                    .edit_groups
1227                    .iter()
1228                    .map(|(buffer, groups)| ProposedChangeLocation {
1229                        buffer: buffer.clone(),
1230                        ranges: groups
1231                            .iter()
1232                            .map(|group| group.context_range.clone())
1233                            .collect(),
1234                    })
1235                    .collect(),
1236                Some(project.clone()),
1237                window,
1238                cx,
1239            );
1240            resolved_patch.apply(&editor, cx);
1241            editor
1242        })?;
1243
1244        this.update(cx, |this, _| {
1245            if let Some(patch_state) = this.patches.get_mut(&patch.range) {
1246                patch_state.editor = Some(PatchEditorState {
1247                    editor: editor.downgrade(),
1248                    opened_patch: patch,
1249                });
1250                patch_state.update_task.take();
1251            }
1252        })?;
1253        this.read_with(cx, |this, _| this.workspace.clone())?
1254            .update_in(cx, |workspace, window, cx| {
1255                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, window, cx)
1256            })
1257            .log_err();
1258
1259        Ok(())
1260    }
1261
1262    async fn update_patch_editor(
1263        this: WeakEntity<Self>,
1264        patch: AssistantPatch,
1265        cx: &mut AsyncWindowContext,
1266    ) -> Result<()> {
1267        let project = this.update(cx, |this, _| this.project.clone())?;
1268        let resolved_patch = patch.resolve(project.clone(), cx).await;
1269        this.update_in(cx, |this, window, cx| {
1270            let patch_state = this.patches.get_mut(&patch.range)?;
1271
1272            let locations = resolved_patch
1273                .edit_groups
1274                .iter()
1275                .map(|(buffer, groups)| ProposedChangeLocation {
1276                    buffer: buffer.clone(),
1277                    ranges: groups
1278                        .iter()
1279                        .map(|group| group.context_range.clone())
1280                        .collect(),
1281                })
1282                .collect();
1283
1284            if let Some(state) = &mut patch_state.editor {
1285                if let Some(editor) = state.editor.upgrade() {
1286                    editor.update(cx, |editor, cx| {
1287                        editor.set_title(patch.title.clone(), cx);
1288                        editor.reset_locations(locations, window, cx);
1289                        resolved_patch.apply(editor, cx);
1290                    });
1291
1292                    state.opened_patch = patch;
1293                } else {
1294                    patch_state.editor.take();
1295                }
1296            }
1297            patch_state.update_task.take();
1298
1299            Some(())
1300        })?;
1301        Ok(())
1302    }
1303
1304    fn handle_editor_search_event(
1305        &mut self,
1306        _: &Entity<Editor>,
1307        event: &SearchEvent,
1308        _window: &mut Window,
1309        cx: &mut Context<Self>,
1310    ) {
1311        cx.emit(event.clone());
1312    }
1313
1314    fn cursor_scroll_position(
1315        &self,
1316        window: &mut Window,
1317        cx: &mut Context<Self>,
1318    ) -> Option<ScrollPosition> {
1319        self.editor.update(cx, |editor, cx| {
1320            let snapshot = editor.snapshot(window, cx);
1321            let cursor = editor.selections.newest_anchor().head();
1322            let cursor_row = cursor
1323                .to_display_point(&snapshot.display_snapshot)
1324                .row()
1325                .as_f32();
1326            let scroll_position = editor
1327                .scroll_manager
1328                .anchor()
1329                .scroll_position(&snapshot.display_snapshot);
1330
1331            let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
1332            if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
1333                Some(ScrollPosition {
1334                    cursor,
1335                    offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
1336                })
1337            } else {
1338                None
1339            }
1340        })
1341    }
1342
1343    fn esc_kbd(cx: &App) -> Div {
1344        let colors = cx.theme().colors().clone();
1345
1346        h_flex()
1347            .items_center()
1348            .gap_1()
1349            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
1350            .text_size(TextSize::XSmall.rems(cx))
1351            .text_color(colors.text_muted)
1352            .child("Press")
1353            .child(
1354                h_flex()
1355                    .rounded_sm()
1356                    .px_1()
1357                    .mr_0p5()
1358                    .border_1()
1359                    .border_color(colors.border_variant.alpha(0.6))
1360                    .bg(colors.element_background.alpha(0.6))
1361                    .child("esc"),
1362            )
1363            .child("to cancel")
1364    }
1365
1366    fn update_message_headers(&mut self, cx: &mut Context<Self>) {
1367        self.editor.update(cx, |editor, cx| {
1368            let buffer = editor.buffer().read(cx).snapshot(cx);
1369
1370            let excerpt_id = *buffer.as_singleton().unwrap().0;
1371            let mut old_blocks = std::mem::take(&mut self.blocks);
1372            let mut blocks_to_remove: HashMap<_, _> = old_blocks
1373                .iter()
1374                .map(|(message_id, (_, block_id))| (*message_id, *block_id))
1375                .collect();
1376            let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
1377
1378            let render_block = |message: MessageMetadata| -> RenderBlock {
1379                Arc::new({
1380                    let context = self.context.clone();
1381
1382                    move |cx| {
1383                        let message_id = MessageId(message.timestamp);
1384                        let llm_loading = message.role == Role::Assistant
1385                            && message.status == MessageStatus::Pending;
1386
1387                        let (label, spinner, note) = match message.role {
1388                            Role::User => (
1389                                Label::new("You").color(Color::Default).into_any_element(),
1390                                None,
1391                                None,
1392                            ),
1393                            Role::Assistant => {
1394                                let base_label = Label::new("Assistant").color(Color::Info);
1395                                let mut spinner = None;
1396                                let mut note = None;
1397                                let animated_label = if llm_loading {
1398                                    base_label
1399                                        .with_animation(
1400                                            "pulsating-label",
1401                                            Animation::new(Duration::from_secs(2))
1402                                                .repeat()
1403                                                .with_easing(pulsating_between(0.4, 0.8)),
1404                                            |label, delta| label.alpha(delta),
1405                                        )
1406                                        .into_any_element()
1407                                } else {
1408                                    base_label.into_any_element()
1409                                };
1410                                if llm_loading {
1411                                    spinner = Some(
1412                                        Icon::new(IconName::ArrowCircle)
1413                                            .size(IconSize::XSmall)
1414                                            .color(Color::Info)
1415                                            .with_animation(
1416                                                "arrow-circle",
1417                                                Animation::new(Duration::from_secs(2)).repeat(),
1418                                                |icon, delta| {
1419                                                    icon.transform(Transformation::rotate(
1420                                                        percentage(delta),
1421                                                    ))
1422                                                },
1423                                            )
1424                                            .into_any_element(),
1425                                    );
1426                                    note = Some(Self::esc_kbd(cx).into_any_element());
1427                                }
1428                                (animated_label, spinner, note)
1429                            }
1430                            Role::System => (
1431                                Label::new("System")
1432                                    .color(Color::Warning)
1433                                    .into_any_element(),
1434                                None,
1435                                None,
1436                            ),
1437                        };
1438
1439                        let sender = h_flex()
1440                            .items_center()
1441                            .gap_2p5()
1442                            .child(
1443                                ButtonLike::new("role")
1444                                    .style(ButtonStyle::Filled)
1445                                    .child(
1446                                        h_flex()
1447                                            .items_center()
1448                                            .gap_1p5()
1449                                            .child(label)
1450                                            .children(spinner),
1451                                    )
1452                                    .tooltip(|window, cx| {
1453                                        Tooltip::with_meta(
1454                                            "Toggle message role",
1455                                            None,
1456                                            "Available roles: You (User), Assistant, System",
1457                                            window,
1458                                            cx,
1459                                        )
1460                                    })
1461                                    .on_click({
1462                                        let context = context.clone();
1463                                        move |_, _window, cx| {
1464                                            context.update(cx, |context, cx| {
1465                                                context.cycle_message_roles(
1466                                                    HashSet::from_iter(Some(message_id)),
1467                                                    cx,
1468                                                )
1469                                            })
1470                                        }
1471                                    }),
1472                            )
1473                            .children(note);
1474
1475                        h_flex()
1476                            .id(("message_header", message_id.as_u64()))
1477                            .pl(cx.gutter_dimensions.full_width())
1478                            .h_11()
1479                            .w_full()
1480                            .relative()
1481                            .gap_1p5()
1482                            .child(sender)
1483                            .children(match &message.cache {
1484                                Some(cache) if cache.is_final_anchor => match cache.status {
1485                                    CacheStatus::Cached => Some(
1486                                        div()
1487                                            .id("cached")
1488                                            .child(
1489                                                Icon::new(IconName::DatabaseZap)
1490                                                    .size(IconSize::XSmall)
1491                                                    .color(Color::Hint),
1492                                            )
1493                                            .tooltip(|window, cx| {
1494                                                Tooltip::with_meta(
1495                                                    "Context Cached",
1496                                                    None,
1497                                                    "Large messages cached to optimize performance",
1498                                                    window,
1499                                                    cx,
1500                                                )
1501                                            })
1502                                            .into_any_element(),
1503                                    ),
1504                                    CacheStatus::Pending => Some(
1505                                        div()
1506                                            .child(
1507                                                Icon::new(IconName::Ellipsis)
1508                                                    .size(IconSize::XSmall)
1509                                                    .color(Color::Hint),
1510                                            )
1511                                            .into_any_element(),
1512                                    ),
1513                                },
1514                                _ => None,
1515                            })
1516                            .children(match &message.status {
1517                                MessageStatus::Error(error) => Some(
1518                                    Button::new("show-error", "Error")
1519                                        .color(Color::Error)
1520                                        .selected_label_color(Color::Error)
1521                                        .selected_icon_color(Color::Error)
1522                                        .icon(IconName::XCircle)
1523                                        .icon_color(Color::Error)
1524                                        .icon_size(IconSize::XSmall)
1525                                        .icon_position(IconPosition::Start)
1526                                        .tooltip(Tooltip::text("View Details"))
1527                                        .on_click({
1528                                            let context = context.clone();
1529                                            let error = error.clone();
1530                                            move |_, _window, cx| {
1531                                                context.update(cx, |_, cx| {
1532                                                    cx.emit(ContextEvent::ShowAssistError(
1533                                                        error.clone(),
1534                                                    ));
1535                                                });
1536                                            }
1537                                        })
1538                                        .into_any_element(),
1539                                ),
1540                                MessageStatus::Canceled => Some(
1541                                    h_flex()
1542                                        .gap_1()
1543                                        .items_center()
1544                                        .child(
1545                                            Icon::new(IconName::XCircle)
1546                                                .color(Color::Disabled)
1547                                                .size(IconSize::XSmall),
1548                                        )
1549                                        .child(
1550                                            Label::new("Canceled")
1551                                                .size(LabelSize::Small)
1552                                                .color(Color::Disabled),
1553                                        )
1554                                        .into_any_element(),
1555                                ),
1556                                _ => None,
1557                            })
1558                            .into_any_element()
1559                    }
1560                })
1561            };
1562            let create_block_properties = |message: &Message| BlockProperties {
1563                height: 2,
1564                style: BlockStyle::Sticky,
1565                placement: BlockPlacement::Above(
1566                    buffer
1567                        .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
1568                        .unwrap(),
1569                ),
1570                priority: usize::MAX,
1571                render: render_block(MessageMetadata::from(message)),
1572            };
1573            let mut new_blocks = vec![];
1574            let mut block_index_to_message = vec![];
1575            for message in self.context.read(cx).messages(cx) {
1576                if let Some(_) = blocks_to_remove.remove(&message.id) {
1577                    // This is an old message that we might modify.
1578                    let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
1579                        debug_assert!(
1580                            false,
1581                            "old_blocks should contain a message_id we've just removed."
1582                        );
1583                        continue;
1584                    };
1585                    // Should we modify it?
1586                    let message_meta = MessageMetadata::from(&message);
1587                    if meta != &message_meta {
1588                        blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
1589                        *meta = message_meta;
1590                    }
1591                } else {
1592                    // This is a new message.
1593                    new_blocks.push(create_block_properties(&message));
1594                    block_index_to_message.push((message.id, MessageMetadata::from(&message)));
1595                }
1596            }
1597            editor.replace_blocks(blocks_to_replace, None, cx);
1598            editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
1599
1600            let ids = editor.insert_blocks(new_blocks, None, cx);
1601            old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
1602                |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
1603            ));
1604            self.blocks = old_blocks;
1605        });
1606    }
1607
1608    /// Returns either the selected text, or the content of the Markdown code
1609    /// block surrounding the cursor.
1610    fn get_selection_or_code_block(
1611        context_editor_view: &Entity<ContextEditor>,
1612        cx: &mut Context<Workspace>,
1613    ) -> Option<(String, bool)> {
1614        const CODE_FENCE_DELIMITER: &'static str = "```";
1615
1616        let context_editor = context_editor_view.read(cx).editor.clone();
1617        context_editor.update(cx, |context_editor, cx| {
1618            if context_editor.selections.newest::<Point>(cx).is_empty() {
1619                let snapshot = context_editor.buffer().read(cx).snapshot(cx);
1620                let (_, _, snapshot) = snapshot.as_singleton()?;
1621
1622                let head = context_editor.selections.newest::<Point>(cx).head();
1623                let offset = snapshot.point_to_offset(head);
1624
1625                let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
1626                let mut text = snapshot
1627                    .text_for_range(surrounding_code_block_range)
1628                    .collect::<String>();
1629
1630                // If there is no newline trailing the closing three-backticks, then
1631                // tree-sitter-md extends the range of the content node to include
1632                // the backticks.
1633                if text.ends_with(CODE_FENCE_DELIMITER) {
1634                    text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
1635                }
1636
1637                (!text.is_empty()).then_some((text, true))
1638            } else {
1639                let selection = context_editor.selections.newest_adjusted(cx);
1640                let buffer = context_editor.buffer().read(cx).snapshot(cx);
1641                let selected_text = buffer.text_for_range(selection.range()).collect::<String>();
1642
1643                (!selected_text.is_empty()).then_some((selected_text, false))
1644            }
1645        })
1646    }
1647
1648    pub fn insert_selection(
1649        workspace: &mut Workspace,
1650        _: &InsertIntoEditor,
1651        window: &mut Window,
1652        cx: &mut Context<Workspace>,
1653    ) {
1654        let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1655            return;
1656        };
1657        let Some(context_editor_view) =
1658            assistant_panel_delegate.active_context_editor(workspace, window, cx)
1659        else {
1660            return;
1661        };
1662        let Some(active_editor_view) = workspace
1663            .active_item(cx)
1664            .and_then(|item| item.act_as::<Editor>(cx))
1665        else {
1666            return;
1667        };
1668
1669        if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
1670            active_editor_view.update(cx, |editor, cx| {
1671                editor.insert(&text, window, cx);
1672                editor.focus_handle(cx).focus(window);
1673            })
1674        }
1675    }
1676
1677    pub fn copy_code(
1678        workspace: &mut Workspace,
1679        _: &CopyCode,
1680        window: &mut Window,
1681        cx: &mut Context<Workspace>,
1682    ) {
1683        let result = maybe!({
1684            let assistant_panel_delegate = <dyn AssistantPanelDelegate>::try_global(cx)?;
1685            let context_editor_view =
1686                assistant_panel_delegate.active_context_editor(workspace, window, cx)?;
1687            Self::get_selection_or_code_block(&context_editor_view, cx)
1688        });
1689        let Some((text, is_code_block)) = result else {
1690            return;
1691        };
1692
1693        cx.write_to_clipboard(ClipboardItem::new_string(text));
1694
1695        struct CopyToClipboardToast;
1696        workspace.show_toast(
1697            Toast::new(
1698                NotificationId::unique::<CopyToClipboardToast>(),
1699                format!(
1700                    "{} copied to clipboard.",
1701                    if is_code_block {
1702                        "Code block"
1703                    } else {
1704                        "Selection"
1705                    }
1706                ),
1707            )
1708            .autohide(),
1709            cx,
1710        );
1711    }
1712
1713    pub fn insert_dragged_files(
1714        workspace: &mut Workspace,
1715        action: &InsertDraggedFiles,
1716        window: &mut Window,
1717        cx: &mut Context<Workspace>,
1718    ) {
1719        let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1720            return;
1721        };
1722        let Some(context_editor_view) =
1723            assistant_panel_delegate.active_context_editor(workspace, window, cx)
1724        else {
1725            return;
1726        };
1727
1728        let project = workspace.project().clone();
1729
1730        let paths = match action {
1731            InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
1732            InsertDraggedFiles::ExternalFiles(paths) => {
1733                let tasks = paths
1734                    .clone()
1735                    .into_iter()
1736                    .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
1737                    .collect::<Vec<_>>();
1738
1739                cx.spawn(async move |_, cx| {
1740                    let mut paths = vec![];
1741                    let mut worktrees = vec![];
1742
1743                    let opened_paths = futures::future::join_all(tasks).await;
1744                    for (worktree, project_path) in opened_paths.into_iter().flatten() {
1745                        let Ok(worktree_root_name) =
1746                            worktree.read_with(cx, |worktree, _| worktree.root_name().to_string())
1747                        else {
1748                            continue;
1749                        };
1750
1751                        let mut full_path = PathBuf::from(worktree_root_name.clone());
1752                        full_path.push(&project_path.path);
1753                        paths.push(full_path);
1754                        worktrees.push(worktree);
1755                    }
1756
1757                    (paths, worktrees)
1758                })
1759            }
1760        };
1761
1762        window
1763            .spawn(cx, async move |cx| {
1764                let (paths, dragged_file_worktrees) = paths.await;
1765                let cmd_name = FileSlashCommand.name();
1766
1767                context_editor_view
1768                    .update_in(cx, |context_editor, window, cx| {
1769                        let file_argument = paths
1770                            .into_iter()
1771                            .map(|path| path.to_string_lossy().to_string())
1772                            .collect::<Vec<_>>()
1773                            .join(" ");
1774
1775                        context_editor.editor.update(cx, |editor, cx| {
1776                            editor.insert("\n", window, cx);
1777                            editor.insert(&format!("/{} {}", cmd_name, file_argument), window, cx);
1778                        });
1779
1780                        context_editor.confirm_command(&ConfirmCommand, window, cx);
1781
1782                        context_editor
1783                            .dragged_file_worktrees
1784                            .extend(dragged_file_worktrees);
1785                    })
1786                    .log_err();
1787            })
1788            .detach();
1789    }
1790
1791    pub fn quote_selection(
1792        workspace: &mut Workspace,
1793        _: &QuoteSelection,
1794        window: &mut Window,
1795        cx: &mut Context<Workspace>,
1796    ) {
1797        let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1798            return;
1799        };
1800
1801        let Some(creases) = selections_creases(workspace, cx) else {
1802            return;
1803        };
1804
1805        if creases.is_empty() {
1806            return;
1807        }
1808
1809        assistant_panel_delegate.quote_selection(workspace, creases, window, cx);
1810    }
1811
1812    pub fn quote_creases(
1813        &mut self,
1814        creases: Vec<(String, String)>,
1815        window: &mut Window,
1816        cx: &mut Context<Self>,
1817    ) {
1818        self.editor.update(cx, |editor, cx| {
1819            editor.insert("\n", window, cx);
1820            for (text, crease_title) in creases {
1821                let point = editor.selections.newest::<Point>(cx).head();
1822                let start_row = MultiBufferRow(point.row);
1823
1824                editor.insert(&text, window, cx);
1825
1826                let snapshot = editor.buffer().read(cx).snapshot(cx);
1827                let anchor_before = snapshot.anchor_after(point);
1828                let anchor_after = editor
1829                    .selections
1830                    .newest_anchor()
1831                    .head()
1832                    .bias_left(&snapshot);
1833
1834                editor.insert("\n", window, cx);
1835
1836                let fold_placeholder =
1837                    quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1838                let crease = Crease::inline(
1839                    anchor_before..anchor_after,
1840                    fold_placeholder,
1841                    render_quote_selection_output_toggle,
1842                    |_, _, _, _| Empty.into_any(),
1843                );
1844                editor.insert_creases(vec![crease], cx);
1845                editor.fold_at(
1846                    &FoldAt {
1847                        buffer_row: start_row,
1848                    },
1849                    window,
1850                    cx,
1851                );
1852            }
1853        })
1854    }
1855
1856    fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1857        if self.editor.read(cx).selections.count() == 1 {
1858            let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1859            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1860                copied_text,
1861                metadata,
1862            ));
1863            cx.stop_propagation();
1864            return;
1865        }
1866
1867        cx.propagate();
1868    }
1869
1870    fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1871        if self.editor.read(cx).selections.count() == 1 {
1872            let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1873
1874            self.editor.update(cx, |editor, cx| {
1875                editor.transact(window, cx, |this, window, cx| {
1876                    this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1877                        s.select(selections);
1878                    });
1879                    this.insert("", window, cx);
1880                    cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1881                        copied_text,
1882                        metadata,
1883                    ));
1884                });
1885            });
1886
1887            cx.stop_propagation();
1888            return;
1889        }
1890
1891        cx.propagate();
1892    }
1893
1894    fn get_clipboard_contents(
1895        &mut self,
1896        cx: &mut Context<Self>,
1897    ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
1898        let (selection, creases) = self.editor.update(cx, |editor, cx| {
1899            let mut selection = editor.selections.newest_adjusted(cx);
1900            let snapshot = editor.buffer().read(cx).snapshot(cx);
1901
1902            selection.goal = SelectionGoal::None;
1903
1904            let selection_start = snapshot.point_to_offset(selection.start);
1905
1906            (
1907                selection.map(|point| snapshot.point_to_offset(point)),
1908                editor.display_map.update(cx, |display_map, cx| {
1909                    display_map
1910                        .snapshot(cx)
1911                        .crease_snapshot
1912                        .creases_in_range(
1913                            MultiBufferRow(selection.start.row)
1914                                ..MultiBufferRow(selection.end.row + 1),
1915                            &snapshot,
1916                        )
1917                        .filter_map(|crease| {
1918                            if let Crease::Inline {
1919                                range, metadata, ..
1920                            } = &crease
1921                            {
1922                                let metadata = metadata.as_ref()?;
1923                                let start = range
1924                                    .start
1925                                    .to_offset(&snapshot)
1926                                    .saturating_sub(selection_start);
1927                                let end = range
1928                                    .end
1929                                    .to_offset(&snapshot)
1930                                    .saturating_sub(selection_start);
1931
1932                                let range_relative_to_selection = start..end;
1933                                if !range_relative_to_selection.is_empty() {
1934                                    return Some(SelectedCreaseMetadata {
1935                                        range_relative_to_selection,
1936                                        crease: metadata.clone(),
1937                                    });
1938                                }
1939                            }
1940                            None
1941                        })
1942                        .collect::<Vec<_>>()
1943                }),
1944            )
1945        });
1946
1947        let context = self.context.read(cx);
1948
1949        let mut text = String::new();
1950        for message in context.messages(cx) {
1951            if message.offset_range.start >= selection.range().end {
1952                break;
1953            } else if message.offset_range.end >= selection.range().start {
1954                let range = cmp::max(message.offset_range.start, selection.range().start)
1955                    ..cmp::min(message.offset_range.end, selection.range().end);
1956                if !range.is_empty() {
1957                    for chunk in context.buffer().read(cx).text_for_range(range) {
1958                        text.push_str(chunk);
1959                    }
1960                    if message.offset_range.end < selection.range().end {
1961                        text.push('\n');
1962                    }
1963                }
1964            }
1965        }
1966
1967        (text, CopyMetadata { creases }, vec![selection])
1968    }
1969
1970    fn paste(
1971        &mut self,
1972        action: &editor::actions::Paste,
1973        window: &mut Window,
1974        cx: &mut Context<Self>,
1975    ) {
1976        cx.stop_propagation();
1977
1978        let images = if let Some(item) = cx.read_from_clipboard() {
1979            item.into_entries()
1980                .filter_map(|entry| {
1981                    if let ClipboardEntry::Image(image) = entry {
1982                        Some(image)
1983                    } else {
1984                        None
1985                    }
1986                })
1987                .collect()
1988        } else {
1989            Vec::new()
1990        };
1991
1992        let metadata = if let Some(item) = cx.read_from_clipboard() {
1993            item.entries().first().and_then(|entry| {
1994                if let ClipboardEntry::String(text) = entry {
1995                    text.metadata_json::<CopyMetadata>()
1996                } else {
1997                    None
1998                }
1999            })
2000        } else {
2001            None
2002        };
2003
2004        if images.is_empty() {
2005            self.editor.update(cx, |editor, cx| {
2006                let paste_position = editor.selections.newest::<usize>(cx).head();
2007                editor.paste(action, window, cx);
2008
2009                if let Some(metadata) = metadata {
2010                    let buffer = editor.buffer().read(cx).snapshot(cx);
2011
2012                    let mut buffer_rows_to_fold = BTreeSet::new();
2013                    let weak_editor = cx.entity().downgrade();
2014                    editor.insert_creases(
2015                        metadata.creases.into_iter().map(|metadata| {
2016                            let start = buffer.anchor_after(
2017                                paste_position + metadata.range_relative_to_selection.start,
2018                            );
2019                            let end = buffer.anchor_before(
2020                                paste_position + metadata.range_relative_to_selection.end,
2021                            );
2022
2023                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2024                            buffer_rows_to_fold.insert(buffer_row);
2025                            Crease::inline(
2026                                start..end,
2027                                FoldPlaceholder {
2028                                    render: render_fold_icon_button(
2029                                        weak_editor.clone(),
2030                                        metadata.crease.icon,
2031                                        metadata.crease.label.clone(),
2032                                    ),
2033                                    ..Default::default()
2034                                },
2035                                render_slash_command_output_toggle,
2036                                |_, _, _, _| Empty.into_any(),
2037                            )
2038                            .with_metadata(metadata.crease.clone())
2039                        }),
2040                        cx,
2041                    );
2042                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2043                        editor.fold_at(&FoldAt { buffer_row }, window, cx);
2044                    }
2045                }
2046            });
2047        } else {
2048            let mut image_positions = Vec::new();
2049            self.editor.update(cx, |editor, cx| {
2050                editor.transact(window, cx, |editor, _window, cx| {
2051                    let edits = editor
2052                        .selections
2053                        .all::<usize>(cx)
2054                        .into_iter()
2055                        .map(|selection| (selection.start..selection.end, "\n"));
2056                    editor.edit(edits, cx);
2057
2058                    let snapshot = editor.buffer().read(cx).snapshot(cx);
2059                    for selection in editor.selections.all::<usize>(cx) {
2060                        image_positions.push(snapshot.anchor_before(selection.end));
2061                    }
2062                });
2063            });
2064
2065            self.context.update(cx, |context, cx| {
2066                for image in images {
2067                    let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
2068                    else {
2069                        continue;
2070                    };
2071                    let image_id = image.id();
2072                    let image_task = LanguageModelImage::from_image(image, cx).shared();
2073
2074                    for image_position in image_positions.iter() {
2075                        context.insert_content(
2076                            Content::Image {
2077                                anchor: image_position.text_anchor,
2078                                image_id,
2079                                image: image_task.clone(),
2080                                render_image: render_image.clone(),
2081                            },
2082                            cx,
2083                        );
2084                    }
2085                }
2086            });
2087        }
2088    }
2089
2090    fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
2091        self.editor.update(cx, |editor, cx| {
2092            let buffer = editor.buffer().read(cx).snapshot(cx);
2093            let excerpt_id = *buffer.as_singleton().unwrap().0;
2094            let old_blocks = std::mem::take(&mut self.image_blocks);
2095            let new_blocks = self
2096                .context
2097                .read(cx)
2098                .contents(cx)
2099                .map(
2100                    |Content::Image {
2101                         anchor,
2102                         render_image,
2103                         ..
2104                     }| (anchor, render_image),
2105                )
2106                .filter_map(|(anchor, render_image)| {
2107                    const MAX_HEIGHT_IN_LINES: u32 = 8;
2108                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
2109                    let image = render_image.clone();
2110                    anchor.is_valid(&buffer).then(|| BlockProperties {
2111                        placement: BlockPlacement::Above(anchor),
2112                        height: MAX_HEIGHT_IN_LINES,
2113                        style: BlockStyle::Sticky,
2114                        render: Arc::new(move |cx| {
2115                            let image_size = size_for_image(
2116                                &image,
2117                                size(
2118                                    cx.max_width - cx.gutter_dimensions.full_width(),
2119                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
2120                                ),
2121                            );
2122                            h_flex()
2123                                .pl(cx.gutter_dimensions.full_width())
2124                                .child(
2125                                    img(image.clone())
2126                                        .object_fit(gpui::ObjectFit::ScaleDown)
2127                                        .w(image_size.width)
2128                                        .h(image_size.height),
2129                                )
2130                                .into_any_element()
2131                        }),
2132                        priority: 0,
2133                    })
2134                })
2135                .collect::<Vec<_>>();
2136
2137            editor.remove_blocks(old_blocks, None, cx);
2138            let ids = editor.insert_blocks(new_blocks, None, cx);
2139            self.image_blocks = HashSet::from_iter(ids);
2140        });
2141    }
2142
2143    fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
2144        self.context.update(cx, |context, cx| {
2145            let selections = self.editor.read(cx).selections.disjoint_anchors();
2146            for selection in selections.as_ref() {
2147                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2148                let range = selection
2149                    .map(|endpoint| endpoint.to_offset(&buffer))
2150                    .range();
2151                context.split_message(range, cx);
2152            }
2153        });
2154    }
2155
2156    fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
2157        self.context.update(cx, |context, cx| {
2158            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
2159        });
2160    }
2161
2162    pub fn title(&self, cx: &App) -> Cow<str> {
2163        self.context
2164            .read(cx)
2165            .summary()
2166            .map(|summary| summary.text.clone())
2167            .map(Cow::Owned)
2168            .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
2169    }
2170
2171    fn render_patch_block(
2172        &mut self,
2173        range: Range<text::Anchor>,
2174        max_width: Pixels,
2175        gutter_width: Pixels,
2176        id: BlockId,
2177        selected: bool,
2178        window: &mut Window,
2179        cx: &mut Context<Self>,
2180    ) -> Option<AnyElement> {
2181        let snapshot = self
2182            .editor
2183            .update(cx, |editor, cx| editor.snapshot(window, cx));
2184        let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
2185        let excerpt_id = *excerpt_id;
2186        let anchor = snapshot
2187            .buffer_snapshot
2188            .anchor_in_excerpt(excerpt_id, range.start)
2189            .unwrap();
2190
2191        let theme = cx.theme().clone();
2192        let patch = self.context.read(cx).patch_for_range(&range, cx)?;
2193        let paths = patch
2194            .paths()
2195            .map(|p| SharedString::from(p.to_string()))
2196            .collect::<BTreeSet<_>>();
2197
2198        Some(
2199            v_flex()
2200                .id(id)
2201                .bg(theme.colors().editor_background)
2202                .ml(gutter_width)
2203                .pb_1()
2204                .w(max_width - gutter_width)
2205                .rounded_sm()
2206                .border_1()
2207                .border_color(theme.colors().border_variant)
2208                .overflow_hidden()
2209                .hover(|style| style.border_color(theme.colors().text_accent))
2210                .when(selected, |this| {
2211                    this.border_color(theme.colors().text_accent)
2212                })
2213                .cursor(CursorStyle::PointingHand)
2214                .on_click(cx.listener(move |this, _, window, cx| {
2215                    this.editor.update(cx, |editor, cx| {
2216                        editor.change_selections(None, window, cx, |selections| {
2217                            selections.select_ranges(vec![anchor..anchor]);
2218                        });
2219                    });
2220                    this.focus_active_patch(window, cx);
2221                }))
2222                .child(
2223                    div()
2224                        .px_2()
2225                        .py_1()
2226                        .overflow_hidden()
2227                        .text_ellipsis()
2228                        .border_b_1()
2229                        .border_color(theme.colors().border_variant)
2230                        .bg(theme.colors().element_background)
2231                        .child(
2232                            Label::new(patch.title.clone())
2233                                .size(LabelSize::Small)
2234                                .color(Color::Muted),
2235                        ),
2236                )
2237                .children(paths.into_iter().map(|path| {
2238                    h_flex()
2239                        .px_2()
2240                        .pt_1()
2241                        .gap_1p5()
2242                        .child(Icon::new(IconName::File).size(IconSize::Small))
2243                        .child(Label::new(path).size(LabelSize::Small))
2244                }))
2245                .when(patch.status == AssistantPatchStatus::Pending, |div| {
2246                    div.child(
2247                        h_flex()
2248                            .pt_1()
2249                            .px_2()
2250                            .gap_1()
2251                            .child(
2252                                Icon::new(IconName::ArrowCircle)
2253                                    .size(IconSize::XSmall)
2254                                    .color(Color::Muted)
2255                                    .with_animation(
2256                                        "arrow-circle",
2257                                        Animation::new(Duration::from_secs(2)).repeat(),
2258                                        |icon, delta| {
2259                                            icon.transform(Transformation::rotate(percentage(
2260                                                delta,
2261                                            )))
2262                                        },
2263                                    ),
2264                            )
2265                            .child(
2266                                Label::new("Generating…")
2267                                    .color(Color::Muted)
2268                                    .size(LabelSize::Small)
2269                                    .with_animation(
2270                                        "pulsating-label",
2271                                        Animation::new(Duration::from_secs(2))
2272                                            .repeat()
2273                                            .with_easing(pulsating_between(0.4, 0.8)),
2274                                        |label, delta| label.alpha(delta),
2275                                    ),
2276                            ),
2277                    )
2278                })
2279                .into_any(),
2280        )
2281    }
2282
2283    fn render_notice(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2284        // This was previously gated behind the `zed-pro` feature flag. Since we
2285        // aren't planning to ship that right now, we're just hard-coding this
2286        // value to not show the nudge.
2287        let nudge = Some(false);
2288
2289        if nudge.map_or(false, |value| value) {
2290            Some(
2291                h_flex()
2292                    .p_3()
2293                    .border_b_1()
2294                    .border_color(cx.theme().colors().border_variant)
2295                    .bg(cx.theme().colors().editor_background)
2296                    .justify_between()
2297                    .child(
2298                        h_flex()
2299                            .gap_3()
2300                            .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
2301                            .child(Label::new("Zed AI is here! Get started by signing in →")),
2302                    )
2303                    .child(
2304                        Button::new("sign-in", "Sign in")
2305                            .size(ButtonSize::Compact)
2306                            .style(ButtonStyle::Filled)
2307                            .on_click(cx.listener(|this, _event, _window, cx| {
2308                                let client = this
2309                                    .workspace
2310                                    .update(cx, |workspace, _| workspace.client().clone())
2311                                    .log_err();
2312
2313                                if let Some(client) = client {
2314                                    cx.spawn(async move |this, cx| {
2315                                        client.authenticate_and_connect(true, cx).await?;
2316                                        this.update(cx, |_, cx| cx.notify())
2317                                    })
2318                                    .detach_and_log_err(cx)
2319                                }
2320                            })),
2321                    )
2322                    .into_any_element(),
2323            )
2324        } else if let Some(configuration_error) = configuration_error(cx) {
2325            let label = match configuration_error {
2326                ConfigurationError::NoProvider => "No LLM provider selected.",
2327                ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
2328                ConfigurationError::ProviderPendingTermsAcceptance(_) => {
2329                    "LLM provider requires accepting the Terms of Service."
2330                }
2331            };
2332            Some(
2333                h_flex()
2334                    .px_3()
2335                    .py_2()
2336                    .border_b_1()
2337                    .border_color(cx.theme().colors().border_variant)
2338                    .bg(cx.theme().colors().editor_background)
2339                    .justify_between()
2340                    .child(
2341                        h_flex()
2342                            .gap_3()
2343                            .child(
2344                                Icon::new(IconName::Warning)
2345                                    .size(IconSize::Small)
2346                                    .color(Color::Warning),
2347                            )
2348                            .child(Label::new(label)),
2349                    )
2350                    .child(
2351                        Button::new("open-configuration", "Configure Providers")
2352                            .size(ButtonSize::Compact)
2353                            .icon(Some(IconName::SlidersVertical))
2354                            .icon_size(IconSize::Small)
2355                            .icon_position(IconPosition::Start)
2356                            .style(ButtonStyle::Filled)
2357                            .on_click({
2358                                let focus_handle = self.focus_handle(cx).clone();
2359                                move |_event, window, cx| {
2360                                    focus_handle.dispatch_action(&ShowConfiguration, window, cx);
2361                                }
2362                            }),
2363                    )
2364                    .into_any_element(),
2365            )
2366        } else {
2367            None
2368        }
2369    }
2370
2371    fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2372        let focus_handle = self.focus_handle(cx).clone();
2373
2374        let (style, tooltip) = match token_state(&self.context, cx) {
2375            Some(TokenState::NoTokensLeft { .. }) => (
2376                ButtonStyle::Tinted(TintColor::Error),
2377                Some(Tooltip::text("Token limit reached")(window, cx)),
2378            ),
2379            Some(TokenState::HasMoreTokens {
2380                over_warn_threshold,
2381                ..
2382            }) => {
2383                let (style, tooltip) = if over_warn_threshold {
2384                    (
2385                        ButtonStyle::Tinted(TintColor::Warning),
2386                        Some(Tooltip::text("Token limit is close to exhaustion")(
2387                            window, cx,
2388                        )),
2389                    )
2390                } else {
2391                    (ButtonStyle::Filled, None)
2392                };
2393                (style, tooltip)
2394            }
2395            None => (ButtonStyle::Filled, None),
2396        };
2397
2398        let provider = LanguageModelRegistry::read_global(cx).active_provider();
2399
2400        let has_configuration_error = configuration_error(cx).is_some();
2401        let needs_to_accept_terms = self.show_accept_terms
2402            && provider
2403                .as_ref()
2404                .map_or(false, |provider| provider.must_accept_terms(cx));
2405        let disabled = has_configuration_error || needs_to_accept_terms;
2406
2407        ButtonLike::new("send_button")
2408            .disabled(disabled)
2409            .style(style)
2410            .when_some(tooltip, |button, tooltip| {
2411                button.tooltip(move |_, _| tooltip.clone())
2412            })
2413            .layer(ElevationIndex::ModalSurface)
2414            .child(Label::new(
2415                if AssistantSettings::get_global(cx).are_live_diffs_enabled(cx) {
2416                    "Chat"
2417                } else {
2418                    "Send"
2419                },
2420            ))
2421            .children(
2422                KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
2423                    .map(|binding| binding.into_any_element()),
2424            )
2425            .on_click(move |_event, window, cx| {
2426                focus_handle.dispatch_action(&Assist, window, cx);
2427            })
2428    }
2429
2430    fn render_edit_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2431        let focus_handle = self.focus_handle(cx).clone();
2432
2433        let (style, tooltip) = match token_state(&self.context, cx) {
2434            Some(TokenState::NoTokensLeft { .. }) => (
2435                ButtonStyle::Tinted(TintColor::Error),
2436                Some(Tooltip::text("Token limit reached")(window, cx)),
2437            ),
2438            Some(TokenState::HasMoreTokens {
2439                over_warn_threshold,
2440                ..
2441            }) => {
2442                let (style, tooltip) = if over_warn_threshold {
2443                    (
2444                        ButtonStyle::Tinted(TintColor::Warning),
2445                        Some(Tooltip::text("Token limit is close to exhaustion")(
2446                            window, cx,
2447                        )),
2448                    )
2449                } else {
2450                    (ButtonStyle::Filled, None)
2451                };
2452                (style, tooltip)
2453            }
2454            None => (ButtonStyle::Filled, None),
2455        };
2456
2457        let provider = LanguageModelRegistry::read_global(cx).active_provider();
2458
2459        let has_configuration_error = configuration_error(cx).is_some();
2460        let needs_to_accept_terms = self.show_accept_terms
2461            && provider
2462                .as_ref()
2463                .map_or(false, |provider| provider.must_accept_terms(cx));
2464        let disabled = has_configuration_error || needs_to_accept_terms;
2465
2466        ButtonLike::new("edit_button")
2467            .disabled(disabled)
2468            .style(style)
2469            .when_some(tooltip, |button, tooltip| {
2470                button.tooltip(move |_, _| tooltip.clone())
2471            })
2472            .layer(ElevationIndex::ModalSurface)
2473            .child(Label::new("Suggest Edits"))
2474            .children(
2475                KeyBinding::for_action_in(&Edit, &focus_handle, window, cx)
2476                    .map(|binding| binding.into_any_element()),
2477            )
2478            .on_click(move |_event, window, cx| {
2479                focus_handle.dispatch_action(&Edit, window, cx);
2480            })
2481    }
2482
2483    fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2484        slash_command_picker::SlashCommandSelector::new(
2485            self.slash_commands.clone(),
2486            cx.entity().downgrade(),
2487            IconButton::new("trigger", IconName::Plus)
2488                .icon_size(IconSize::Small)
2489                .icon_color(Color::Muted),
2490            move |window, cx| {
2491                Tooltip::with_meta(
2492                    "Add Context",
2493                    None,
2494                    "Type / to insert via keyboard",
2495                    window,
2496                    cx,
2497                )
2498            },
2499        )
2500    }
2501
2502    fn render_language_model_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
2503        let active_model = LanguageModelRegistry::read_global(cx).active_model();
2504        let focus_handle = self.editor().focus_handle(cx).clone();
2505        let model_name = match active_model {
2506            Some(model) => model.name().0,
2507            None => SharedString::from("No model selected"),
2508        };
2509
2510        LanguageModelSelectorPopoverMenu::new(
2511            self.language_model_selector.clone(),
2512            ButtonLike::new("active-model")
2513                .style(ButtonStyle::Subtle)
2514                .child(
2515                    h_flex()
2516                        .gap_0p5()
2517                        .child(
2518                            Label::new(model_name)
2519                                .size(LabelSize::Small)
2520                                .color(Color::Muted),
2521                        )
2522                        .child(
2523                            Icon::new(IconName::ChevronDown)
2524                                .color(Color::Muted)
2525                                .size(IconSize::XSmall),
2526                        ),
2527                ),
2528            move |window, cx| {
2529                Tooltip::for_action_in(
2530                    "Change Model",
2531                    &ToggleModelSelector,
2532                    &focus_handle,
2533                    window,
2534                    cx,
2535                )
2536            },
2537            gpui::Corner::BottomLeft,
2538        )
2539        .with_handle(self.language_model_selector_menu_handle.clone())
2540    }
2541
2542    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2543        let last_error = self.last_error.as_ref()?;
2544
2545        Some(
2546            div()
2547                .absolute()
2548                .right_3()
2549                .bottom_12()
2550                .max_w_96()
2551                .py_2()
2552                .px_3()
2553                .elevation_2(cx)
2554                .occlude()
2555                .child(match last_error {
2556                    AssistError::FileRequired => self.render_file_required_error(cx),
2557                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2558                    AssistError::MaxMonthlySpendReached => {
2559                        self.render_max_monthly_spend_reached_error(cx)
2560                    }
2561                    AssistError::Message(error_message) => {
2562                        self.render_assist_error(error_message, cx)
2563                    }
2564                })
2565                .into_any(),
2566        )
2567    }
2568
2569    fn render_file_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2570        v_flex()
2571            .gap_0p5()
2572            .child(
2573                h_flex()
2574                    .gap_1p5()
2575                    .items_center()
2576                    .child(Icon::new(IconName::Warning).color(Color::Warning))
2577                    .child(
2578                        Label::new("Suggest Edits needs a file to edit").weight(FontWeight::MEDIUM),
2579                    ),
2580            )
2581            .child(
2582                div()
2583                    .id("error-message")
2584                    .max_h_24()
2585                    .overflow_y_scroll()
2586                    .child(Label::new(
2587                        "To include files, type /file or /tab in your prompt.",
2588                    )),
2589            )
2590            .child(
2591                h_flex()
2592                    .justify_end()
2593                    .mt_1()
2594                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2595                        |this, _, _window, cx| {
2596                            this.last_error = None;
2597                            cx.notify();
2598                        },
2599                    ))),
2600            )
2601            .into_any()
2602    }
2603
2604    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2605        const ERROR_MESSAGE: &str = "Free tier exceeded. Subscribe and add payment to continue using Zed LLMs. You'll be billed at cost for tokens used.";
2606
2607        v_flex()
2608            .gap_0p5()
2609            .child(
2610                h_flex()
2611                    .gap_1p5()
2612                    .items_center()
2613                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2614                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2615            )
2616            .child(
2617                div()
2618                    .id("error-message")
2619                    .max_h_24()
2620                    .overflow_y_scroll()
2621                    .child(Label::new(ERROR_MESSAGE)),
2622            )
2623            .child(
2624                h_flex()
2625                    .justify_end()
2626                    .mt_1()
2627                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2628                        |this, _, _window, cx| {
2629                            this.last_error = None;
2630                            cx.open_url(&zed_urls::account_url(cx));
2631                            cx.notify();
2632                        },
2633                    )))
2634                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2635                        |this, _, _window, cx| {
2636                            this.last_error = None;
2637                            cx.notify();
2638                        },
2639                    ))),
2640            )
2641            .into_any()
2642    }
2643
2644    fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
2645        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
2646
2647        v_flex()
2648            .gap_0p5()
2649            .child(
2650                h_flex()
2651                    .gap_1p5()
2652                    .items_center()
2653                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2654                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
2655            )
2656            .child(
2657                div()
2658                    .id("error-message")
2659                    .max_h_24()
2660                    .overflow_y_scroll()
2661                    .child(Label::new(ERROR_MESSAGE)),
2662            )
2663            .child(
2664                h_flex()
2665                    .justify_end()
2666                    .mt_1()
2667                    .child(
2668                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
2669                            cx.listener(|this, _, _window, cx| {
2670                                this.last_error = None;
2671                                cx.open_url(&zed_urls::account_url(cx));
2672                                cx.notify();
2673                            }),
2674                        ),
2675                    )
2676                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2677                        |this, _, _window, cx| {
2678                            this.last_error = None;
2679                            cx.notify();
2680                        },
2681                    ))),
2682            )
2683            .into_any()
2684    }
2685
2686    fn render_assist_error(
2687        &self,
2688        error_message: &SharedString,
2689        cx: &mut Context<Self>,
2690    ) -> AnyElement {
2691        v_flex()
2692            .gap_0p5()
2693            .child(
2694                h_flex()
2695                    .gap_1p5()
2696                    .items_center()
2697                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2698                    .child(
2699                        Label::new("Error interacting with language model")
2700                            .weight(FontWeight::MEDIUM),
2701                    ),
2702            )
2703            .child(
2704                div()
2705                    .id("error-message")
2706                    .max_h_32()
2707                    .overflow_y_scroll()
2708                    .child(Label::new(error_message.clone())),
2709            )
2710            .child(
2711                h_flex()
2712                    .justify_end()
2713                    .mt_1()
2714                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2715                        |this, _, _window, cx| {
2716                            this.last_error = None;
2717                            cx.notify();
2718                        },
2719                    ))),
2720            )
2721            .into_any()
2722    }
2723}
2724
2725/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2726fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2727    const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
2728    const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
2729
2730    let layer = snapshot.syntax_layers().next()?;
2731
2732    let root_node = layer.node();
2733    let mut cursor = root_node.walk();
2734
2735    // Go to the first child for the given offset
2736    while cursor.goto_first_child_for_byte(offset).is_some() {
2737        // If we're at the end of the node, go to the next one.
2738        // Example: if you have a fenced-code-block, and you're on the start of the line
2739        // right after the closing ```, you want to skip the fenced-code-block and
2740        // go to the next sibling.
2741        if cursor.node().end_byte() == offset {
2742            cursor.goto_next_sibling();
2743        }
2744
2745        if cursor.node().start_byte() > offset {
2746            break;
2747        }
2748
2749        // We found the fenced code block.
2750        if cursor.node().kind() == CODE_BLOCK_NODE {
2751            // Now we need to find the child node that contains the code.
2752            cursor.goto_first_child();
2753            loop {
2754                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2755                    return Some(cursor.node().byte_range());
2756                }
2757                if !cursor.goto_next_sibling() {
2758                    break;
2759                }
2760            }
2761        }
2762    }
2763
2764    None
2765}
2766
2767fn render_thought_process_fold_icon_button(
2768    editor: WeakEntity<Editor>,
2769    status: ThoughtProcessStatus,
2770) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2771    Arc::new(move |fold_id, fold_range, _cx| {
2772        let editor = editor.clone();
2773
2774        let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2775        let button = match status {
2776            ThoughtProcessStatus::Pending => button
2777                .child(
2778                    Icon::new(IconName::Brain)
2779                        .size(IconSize::Small)
2780                        .color(Color::Muted),
2781                )
2782                .child(
2783                    Label::new("Thinking…").color(Color::Muted).with_animation(
2784                        "pulsating-label",
2785                        Animation::new(Duration::from_secs(2))
2786                            .repeat()
2787                            .with_easing(pulsating_between(0.4, 0.8)),
2788                        |label, delta| label.alpha(delta),
2789                    ),
2790                ),
2791            ThoughtProcessStatus::Completed => button
2792                .style(ButtonStyle::Filled)
2793                .child(Icon::new(IconName::Brain).size(IconSize::Small))
2794                .child(Label::new("Thought Process").single_line()),
2795        };
2796
2797        button
2798            .on_click(move |_, window, cx| {
2799                editor
2800                    .update(cx, |editor, cx| {
2801                        let buffer_start = fold_range
2802                            .start
2803                            .to_point(&editor.buffer().read(cx).read(cx));
2804                        let buffer_row = MultiBufferRow(buffer_start.row);
2805                        editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2806                    })
2807                    .ok();
2808            })
2809            .into_any_element()
2810    })
2811}
2812
2813fn render_fold_icon_button(
2814    editor: WeakEntity<Editor>,
2815    icon: IconName,
2816    label: SharedString,
2817) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2818    Arc::new(move |fold_id, fold_range, _cx| {
2819        let editor = editor.clone();
2820        ButtonLike::new(fold_id)
2821            .style(ButtonStyle::Filled)
2822            .layer(ElevationIndex::ElevatedSurface)
2823            .child(Icon::new(icon))
2824            .child(Label::new(label.clone()).single_line())
2825            .on_click(move |_, window, cx| {
2826                editor
2827                    .update(cx, |editor, cx| {
2828                        let buffer_start = fold_range
2829                            .start
2830                            .to_point(&editor.buffer().read(cx).read(cx));
2831                        let buffer_row = MultiBufferRow(buffer_start.row);
2832                        editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2833                    })
2834                    .ok();
2835            })
2836            .into_any_element()
2837    })
2838}
2839
2840type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2841
2842fn render_slash_command_output_toggle(
2843    row: MultiBufferRow,
2844    is_folded: bool,
2845    fold: ToggleFold,
2846    _window: &mut Window,
2847    _cx: &mut App,
2848) -> AnyElement {
2849    Disclosure::new(
2850        ("slash-command-output-fold-indicator", row.0 as u64),
2851        !is_folded,
2852    )
2853    .toggle_state(is_folded)
2854    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2855    .into_any_element()
2856}
2857
2858pub fn fold_toggle(
2859    name: &'static str,
2860) -> impl Fn(
2861    MultiBufferRow,
2862    bool,
2863    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2864    &mut Window,
2865    &mut App,
2866) -> AnyElement {
2867    move |row, is_folded, fold, _window, _cx| {
2868        Disclosure::new((name, row.0 as u64), !is_folded)
2869            .toggle_state(is_folded)
2870            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2871            .into_any_element()
2872    }
2873}
2874
2875fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2876    FoldPlaceholder {
2877        render: Arc::new({
2878            move |fold_id, fold_range, _cx| {
2879                let editor = editor.clone();
2880                ButtonLike::new(fold_id)
2881                    .style(ButtonStyle::Filled)
2882                    .layer(ElevationIndex::ElevatedSurface)
2883                    .child(Icon::new(IconName::TextSnippet))
2884                    .child(Label::new(title.clone()).single_line())
2885                    .on_click(move |_, window, cx| {
2886                        editor
2887                            .update(cx, |editor, cx| {
2888                                let buffer_start = fold_range
2889                                    .start
2890                                    .to_point(&editor.buffer().read(cx).read(cx));
2891                                let buffer_row = MultiBufferRow(buffer_start.row);
2892                                editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2893                            })
2894                            .ok();
2895                    })
2896                    .into_any_element()
2897            }
2898        }),
2899        merge_adjacent: false,
2900        ..Default::default()
2901    }
2902}
2903
2904fn render_quote_selection_output_toggle(
2905    row: MultiBufferRow,
2906    is_folded: bool,
2907    fold: ToggleFold,
2908    _window: &mut Window,
2909    _cx: &mut App,
2910) -> AnyElement {
2911    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2912        .toggle_state(is_folded)
2913        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2914        .into_any_element()
2915}
2916
2917fn render_pending_slash_command_gutter_decoration(
2918    row: MultiBufferRow,
2919    status: &PendingSlashCommandStatus,
2920    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2921) -> AnyElement {
2922    let mut icon = IconButton::new(
2923        ("slash-command-gutter-decoration", row.0),
2924        ui::IconName::TriangleRight,
2925    )
2926    .on_click(move |_e, window, cx| confirm_command(window, cx))
2927    .icon_size(ui::IconSize::Small)
2928    .size(ui::ButtonSize::None);
2929
2930    match status {
2931        PendingSlashCommandStatus::Idle => {
2932            icon = icon.icon_color(Color::Muted);
2933        }
2934        PendingSlashCommandStatus::Running { .. } => {
2935            icon = icon.toggle_state(true);
2936        }
2937        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2938    }
2939
2940    icon.into_any_element()
2941}
2942
2943fn render_docs_slash_command_trailer(
2944    row: MultiBufferRow,
2945    command: ParsedSlashCommand,
2946    cx: &mut App,
2947) -> AnyElement {
2948    if command.arguments.is_empty() {
2949        return Empty.into_any();
2950    }
2951    let args = DocsSlashCommandArgs::parse(&command.arguments);
2952
2953    let Some(store) = args
2954        .provider()
2955        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
2956    else {
2957        return Empty.into_any();
2958    };
2959
2960    let Some(package) = args.package() else {
2961        return Empty.into_any();
2962    };
2963
2964    let mut children = Vec::new();
2965
2966    if store.is_indexing(&package) {
2967        children.push(
2968            div()
2969                .id(("crates-being-indexed", row.0))
2970                .child(Icon::new(IconName::ArrowCircle).with_animation(
2971                    "arrow-circle",
2972                    Animation::new(Duration::from_secs(4)).repeat(),
2973                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2974                ))
2975                .tooltip({
2976                    let package = package.clone();
2977                    Tooltip::text(format!("Indexing {package}"))
2978                })
2979                .into_any_element(),
2980        );
2981    }
2982
2983    if let Some(latest_error) = store.latest_error_for_package(&package) {
2984        children.push(
2985            div()
2986                .id(("latest-error", row.0))
2987                .child(
2988                    Icon::new(IconName::Warning)
2989                        .size(IconSize::Small)
2990                        .color(Color::Warning),
2991                )
2992                .tooltip(Tooltip::text(format!("Failed to index: {latest_error}")))
2993                .into_any_element(),
2994        )
2995    }
2996
2997    let is_indexing = store.is_indexing(&package);
2998    let latest_error = store.latest_error_for_package(&package);
2999
3000    if !is_indexing && latest_error.is_none() {
3001        return Empty.into_any();
3002    }
3003
3004    h_flex().gap_2().children(children).into_any_element()
3005}
3006
3007#[derive(Debug, Clone, Serialize, Deserialize)]
3008struct CopyMetadata {
3009    creases: Vec<SelectedCreaseMetadata>,
3010}
3011
3012#[derive(Debug, Clone, Serialize, Deserialize)]
3013struct SelectedCreaseMetadata {
3014    range_relative_to_selection: Range<usize>,
3015    crease: CreaseMetadata,
3016}
3017
3018impl EventEmitter<EditorEvent> for ContextEditor {}
3019impl EventEmitter<SearchEvent> for ContextEditor {}
3020
3021impl Render for ContextEditor {
3022    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3023        let provider = LanguageModelRegistry::read_global(cx).active_provider();
3024        let accept_terms = if self.show_accept_terms {
3025            provider.as_ref().and_then(|provider| {
3026                provider.render_accept_terms(LanguageModelProviderTosView::PromptEditorPopup, cx)
3027            })
3028        } else {
3029            None
3030        };
3031
3032        let language_model_selector = self.language_model_selector_menu_handle.clone();
3033        v_flex()
3034            .key_context("ContextEditor")
3035            .capture_action(cx.listener(ContextEditor::cancel))
3036            .capture_action(cx.listener(ContextEditor::save))
3037            .capture_action(cx.listener(ContextEditor::copy))
3038            .capture_action(cx.listener(ContextEditor::cut))
3039            .capture_action(cx.listener(ContextEditor::paste))
3040            .capture_action(cx.listener(ContextEditor::cycle_message_role))
3041            .capture_action(cx.listener(ContextEditor::confirm_command))
3042            .on_action(cx.listener(ContextEditor::edit))
3043            .on_action(cx.listener(ContextEditor::assist))
3044            .on_action(cx.listener(ContextEditor::split))
3045            .on_action(move |_: &ToggleModelSelector, window, cx| {
3046                language_model_selector.toggle(window, cx);
3047            })
3048            .size_full()
3049            .children(self.render_notice(cx))
3050            .child(
3051                div()
3052                    .flex_grow()
3053                    .bg(cx.theme().colors().editor_background)
3054                    .child(self.editor.clone()),
3055            )
3056            .when_some(accept_terms, |this, element| {
3057                this.child(
3058                    div()
3059                        .absolute()
3060                        .right_3()
3061                        .bottom_12()
3062                        .max_w_96()
3063                        .py_2()
3064                        .px_3()
3065                        .elevation_2(cx)
3066                        .bg(cx.theme().colors().surface_background)
3067                        .occlude()
3068                        .child(element),
3069                )
3070            })
3071            .children(self.render_last_error(cx))
3072            .child(
3073                h_flex().w_full().relative().child(
3074                    h_flex()
3075                        .p_2()
3076                        .w_full()
3077                        .border_t_1()
3078                        .border_color(cx.theme().colors().border_variant)
3079                        .bg(cx.theme().colors().editor_background)
3080                        .child(
3081                            h_flex()
3082                                .gap_1()
3083                                .child(self.render_inject_context_menu(cx))
3084                                .child(ui::Divider::vertical())
3085                                .child(
3086                                    div()
3087                                        .pl_0p5()
3088                                        .child(self.render_language_model_selector(cx)),
3089                                ),
3090                        )
3091                        .child(
3092                            h_flex()
3093                                .w_full()
3094                                .justify_end()
3095                                .when(
3096                                    AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
3097                                    |buttons| {
3098                                        buttons
3099                                            .items_center()
3100                                            .gap_1p5()
3101                                            .child(self.render_edit_button(window, cx))
3102                                            .child(
3103                                                Label::new("or")
3104                                                    .size(LabelSize::Small)
3105                                                    .color(Color::Muted),
3106                                            )
3107                                    },
3108                                )
3109                                .child(self.render_send_button(window, cx)),
3110                        ),
3111                ),
3112            )
3113    }
3114}
3115
3116impl Focusable for ContextEditor {
3117    fn focus_handle(&self, cx: &App) -> FocusHandle {
3118        self.editor.focus_handle(cx)
3119    }
3120}
3121
3122impl Item for ContextEditor {
3123    type Event = editor::EditorEvent;
3124
3125    fn tab_content_text(&self, _window: &Window, cx: &App) -> Option<SharedString> {
3126        Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
3127    }
3128
3129    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
3130        match event {
3131            EditorEvent::Edited { .. } => {
3132                f(item::ItemEvent::Edit);
3133            }
3134            EditorEvent::TitleChanged => {
3135                f(item::ItemEvent::UpdateTab);
3136            }
3137            _ => {}
3138        }
3139    }
3140
3141    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
3142        Some(self.title(cx).to_string().into())
3143    }
3144
3145    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
3146        Some(Box::new(handle.clone()))
3147    }
3148
3149    fn set_nav_history(
3150        &mut self,
3151        nav_history: pane::ItemNavHistory,
3152        window: &mut Window,
3153        cx: &mut Context<Self>,
3154    ) {
3155        self.editor.update(cx, |editor, cx| {
3156            Item::set_nav_history(editor, nav_history, window, cx)
3157        })
3158    }
3159
3160    fn navigate(
3161        &mut self,
3162        data: Box<dyn std::any::Any>,
3163        window: &mut Window,
3164        cx: &mut Context<Self>,
3165    ) -> bool {
3166        self.editor
3167            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
3168    }
3169
3170    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3171        self.editor
3172            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
3173    }
3174
3175    fn act_as_type<'a>(
3176        &'a self,
3177        type_id: TypeId,
3178        self_handle: &'a Entity<Self>,
3179        _: &'a App,
3180    ) -> Option<AnyView> {
3181        if type_id == TypeId::of::<Self>() {
3182            Some(self_handle.to_any())
3183        } else if type_id == TypeId::of::<Editor>() {
3184            Some(self.editor.to_any())
3185        } else {
3186            None
3187        }
3188    }
3189
3190    fn include_in_nav_history() -> bool {
3191        false
3192    }
3193}
3194
3195impl SearchableItem for ContextEditor {
3196    type Match = <Editor as SearchableItem>::Match;
3197
3198    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3199        self.editor.update(cx, |editor, cx| {
3200            editor.clear_matches(window, cx);
3201        });
3202    }
3203
3204    fn update_matches(
3205        &mut self,
3206        matches: &[Self::Match],
3207        window: &mut Window,
3208        cx: &mut Context<Self>,
3209    ) {
3210        self.editor
3211            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
3212    }
3213
3214    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
3215        self.editor
3216            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
3217    }
3218
3219    fn activate_match(
3220        &mut self,
3221        index: usize,
3222        matches: &[Self::Match],
3223        window: &mut Window,
3224        cx: &mut Context<Self>,
3225    ) {
3226        self.editor.update(cx, |editor, cx| {
3227            editor.activate_match(index, matches, window, cx);
3228        });
3229    }
3230
3231    fn select_matches(
3232        &mut self,
3233        matches: &[Self::Match],
3234        window: &mut Window,
3235        cx: &mut Context<Self>,
3236    ) {
3237        self.editor
3238            .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
3239    }
3240
3241    fn replace(
3242        &mut self,
3243        identifier: &Self::Match,
3244        query: &project::search::SearchQuery,
3245        window: &mut Window,
3246        cx: &mut Context<Self>,
3247    ) {
3248        self.editor.update(cx, |editor, cx| {
3249            editor.replace(identifier, query, window, cx)
3250        });
3251    }
3252
3253    fn find_matches(
3254        &mut self,
3255        query: Arc<project::search::SearchQuery>,
3256        window: &mut Window,
3257        cx: &mut Context<Self>,
3258    ) -> Task<Vec<Self::Match>> {
3259        self.editor
3260            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
3261    }
3262
3263    fn active_match_index(
3264        &mut self,
3265        direction: Direction,
3266        matches: &[Self::Match],
3267        window: &mut Window,
3268        cx: &mut Context<Self>,
3269    ) -> Option<usize> {
3270        self.editor.update(cx, |editor, cx| {
3271            editor.active_match_index(direction, matches, window, cx)
3272        })
3273    }
3274}
3275
3276impl FollowableItem for ContextEditor {
3277    fn remote_id(&self) -> Option<workspace::ViewId> {
3278        self.remote_id
3279    }
3280
3281    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
3282        let context = self.context.read(cx);
3283        Some(proto::view::Variant::ContextEditor(
3284            proto::view::ContextEditor {
3285                context_id: context.id().to_proto(),
3286                editor: if let Some(proto::view::Variant::Editor(proto)) =
3287                    self.editor.read(cx).to_state_proto(window, cx)
3288                {
3289                    Some(proto)
3290                } else {
3291                    None
3292                },
3293            },
3294        ))
3295    }
3296
3297    fn from_state_proto(
3298        workspace: Entity<Workspace>,
3299        id: workspace::ViewId,
3300        state: &mut Option<proto::view::Variant>,
3301        window: &mut Window,
3302        cx: &mut App,
3303    ) -> Option<Task<Result<Entity<Self>>>> {
3304        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
3305            return None;
3306        };
3307        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
3308            unreachable!()
3309        };
3310
3311        let context_id = ContextId::from_proto(state.context_id);
3312        let editor_state = state.editor?;
3313
3314        let project = workspace.read(cx).project().clone();
3315        let assistant_panel_delegate = <dyn AssistantPanelDelegate>::try_global(cx)?;
3316
3317        let context_editor_task = workspace.update(cx, |workspace, cx| {
3318            assistant_panel_delegate.open_remote_context(workspace, context_id, window, cx)
3319        });
3320
3321        Some(window.spawn(cx, async move |cx| {
3322            let context_editor = context_editor_task.await?;
3323            context_editor
3324                .update_in(cx, |context_editor, window, cx| {
3325                    context_editor.remote_id = Some(id);
3326                    context_editor.editor.update(cx, |editor, cx| {
3327                        editor.apply_update_proto(
3328                            &project,
3329                            proto::update_view::Variant::Editor(proto::update_view::Editor {
3330                                selections: editor_state.selections,
3331                                pending_selection: editor_state.pending_selection,
3332                                scroll_top_anchor: editor_state.scroll_top_anchor,
3333                                scroll_x: editor_state.scroll_y,
3334                                scroll_y: editor_state.scroll_y,
3335                                ..Default::default()
3336                            }),
3337                            window,
3338                            cx,
3339                        )
3340                    })
3341                })?
3342                .await?;
3343            Ok(context_editor)
3344        }))
3345    }
3346
3347    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
3348        Editor::to_follow_event(event)
3349    }
3350
3351    fn add_event_to_update_proto(
3352        &self,
3353        event: &Self::Event,
3354        update: &mut Option<proto::update_view::Variant>,
3355        window: &Window,
3356        cx: &App,
3357    ) -> bool {
3358        self.editor
3359            .read(cx)
3360            .add_event_to_update_proto(event, update, window, cx)
3361    }
3362
3363    fn apply_update_proto(
3364        &mut self,
3365        project: &Entity<Project>,
3366        message: proto::update_view::Variant,
3367        window: &mut Window,
3368        cx: &mut Context<Self>,
3369    ) -> Task<Result<()>> {
3370        self.editor.update(cx, |editor, cx| {
3371            editor.apply_update_proto(project, message, window, cx)
3372        })
3373    }
3374
3375    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
3376        true
3377    }
3378
3379    fn set_leader_peer_id(
3380        &mut self,
3381        leader_peer_id: Option<proto::PeerId>,
3382        window: &mut Window,
3383        cx: &mut Context<Self>,
3384    ) {
3385        self.editor.update(cx, |editor, cx| {
3386            editor.set_leader_peer_id(leader_peer_id, window, cx)
3387        })
3388    }
3389
3390    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
3391        if existing.context.read(cx).id() == self.context.read(cx).id() {
3392            Some(item::Dedup::KeepExisting)
3393        } else {
3394            None
3395        }
3396    }
3397}
3398
3399pub struct ContextEditorToolbarItem {
3400    active_context_editor: Option<WeakEntity<ContextEditor>>,
3401    model_summary_editor: Entity<Editor>,
3402}
3403
3404impl ContextEditorToolbarItem {
3405    pub fn new(model_summary_editor: Entity<Editor>) -> Self {
3406        Self {
3407            active_context_editor: None,
3408            model_summary_editor,
3409        }
3410    }
3411}
3412
3413pub fn render_remaining_tokens(
3414    context_editor: &Entity<ContextEditor>,
3415    cx: &App,
3416) -> Option<impl IntoElement + use<>> {
3417    let context = &context_editor.read(cx).context;
3418
3419    let (token_count_color, token_count, max_token_count, tooltip) = match token_state(context, cx)?
3420    {
3421        TokenState::NoTokensLeft {
3422            max_token_count,
3423            token_count,
3424        } => (
3425            Color::Error,
3426            token_count,
3427            max_token_count,
3428            Some("Token Limit Reached"),
3429        ),
3430        TokenState::HasMoreTokens {
3431            max_token_count,
3432            token_count,
3433            over_warn_threshold,
3434        } => {
3435            let (color, tooltip) = if over_warn_threshold {
3436                (Color::Warning, Some("Token Limit is Close to Exhaustion"))
3437            } else {
3438                (Color::Muted, None)
3439            };
3440            (color, token_count, max_token_count, tooltip)
3441        }
3442    };
3443
3444    Some(
3445        h_flex()
3446            .id("token-count")
3447            .gap_0p5()
3448            .child(
3449                Label::new(humanize_token_count(token_count))
3450                    .size(LabelSize::Small)
3451                    .color(token_count_color),
3452            )
3453            .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
3454            .child(
3455                Label::new(humanize_token_count(max_token_count))
3456                    .size(LabelSize::Small)
3457                    .color(Color::Muted),
3458            )
3459            .when_some(tooltip, |element, tooltip| {
3460                element.tooltip(Tooltip::text(tooltip))
3461            }),
3462    )
3463}
3464
3465impl Render for ContextEditorToolbarItem {
3466    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3467        let left_side = h_flex()
3468            .group("chat-title-group")
3469            .gap_1()
3470            .items_center()
3471            .flex_grow()
3472            .child(
3473                div()
3474                    .w_full()
3475                    .when(self.active_context_editor.is_some(), |left_side| {
3476                        left_side.child(self.model_summary_editor.clone())
3477                    }),
3478            )
3479            .child(
3480                div().visible_on_hover("chat-title-group").child(
3481                    IconButton::new("regenerate-context", IconName::RefreshTitle)
3482                        .shape(ui::IconButtonShape::Square)
3483                        .tooltip(Tooltip::text("Regenerate Title"))
3484                        .on_click(cx.listener(move |_, _, _window, cx| {
3485                            cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3486                        })),
3487                ),
3488            );
3489
3490        let right_side = h_flex()
3491            .gap_2()
3492            // TODO display this in a nicer way, once we have a design for it.
3493            // .children({
3494            //     let project = self
3495            //         .workspace
3496            //         .upgrade()
3497            //         .map(|workspace| workspace.read(cx).project().downgrade());
3498            //
3499            //     let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
3500            //         project.and_then(|project| db.remaining_summaries(&project, cx))
3501            //     });
3502            //     scan_items_remaining
3503            //         .map(|remaining_items| format!("Files to scan: {}", remaining_items))
3504            // })
3505            .children(
3506                self.active_context_editor
3507                    .as_ref()
3508                    .and_then(|editor| editor.upgrade())
3509                    .and_then(|editor| render_remaining_tokens(&editor, cx)),
3510            );
3511
3512        h_flex()
3513            .px_0p5()
3514            .size_full()
3515            .gap_2()
3516            .justify_between()
3517            .child(left_side)
3518            .child(right_side)
3519    }
3520}
3521
3522impl ToolbarItemView for ContextEditorToolbarItem {
3523    fn set_active_pane_item(
3524        &mut self,
3525        active_pane_item: Option<&dyn ItemHandle>,
3526        _window: &mut Window,
3527        cx: &mut Context<Self>,
3528    ) -> ToolbarItemLocation {
3529        self.active_context_editor = active_pane_item
3530            .and_then(|item| item.act_as::<ContextEditor>(cx))
3531            .map(|editor| editor.downgrade());
3532        cx.notify();
3533        if self.active_context_editor.is_none() {
3534            ToolbarItemLocation::Hidden
3535        } else {
3536            ToolbarItemLocation::PrimaryRight
3537        }
3538    }
3539
3540    fn pane_focus_update(
3541        &mut self,
3542        _pane_focused: bool,
3543        _window: &mut Window,
3544        cx: &mut Context<Self>,
3545    ) {
3546        cx.notify();
3547    }
3548}
3549
3550impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
3551
3552pub enum ContextEditorToolbarItemEvent {
3553    RegenerateSummary,
3554}
3555impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
3556
3557enum PendingSlashCommand {}
3558
3559fn invoked_slash_command_fold_placeholder(
3560    command_id: InvokedSlashCommandId,
3561    context: WeakEntity<AssistantContext>,
3562) -> FoldPlaceholder {
3563    FoldPlaceholder {
3564        constrain_width: false,
3565        merge_adjacent: false,
3566        render: Arc::new(move |fold_id, _, cx| {
3567            let Some(context) = context.upgrade() else {
3568                return Empty.into_any();
3569            };
3570
3571            let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
3572                return Empty.into_any();
3573            };
3574
3575            h_flex()
3576                .id(fold_id)
3577                .px_1()
3578                .ml_6()
3579                .gap_2()
3580                .bg(cx.theme().colors().surface_background)
3581                .rounded_sm()
3582                .child(Label::new(format!("/{}", command.name.clone())))
3583                .map(|parent| match &command.status {
3584                    InvokedSlashCommandStatus::Running(_) => {
3585                        parent.child(Icon::new(IconName::ArrowCircle).with_animation(
3586                            "arrow-circle",
3587                            Animation::new(Duration::from_secs(4)).repeat(),
3588                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3589                        ))
3590                    }
3591                    InvokedSlashCommandStatus::Error(message) => parent.child(
3592                        Label::new(format!("error: {message}"))
3593                            .single_line()
3594                            .color(Color::Error),
3595                    ),
3596                    InvokedSlashCommandStatus::Finished => parent,
3597                })
3598                .into_any_element()
3599        }),
3600        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3601    }
3602}
3603
3604enum TokenState {
3605    NoTokensLeft {
3606        max_token_count: usize,
3607        token_count: usize,
3608    },
3609    HasMoreTokens {
3610        max_token_count: usize,
3611        token_count: usize,
3612        over_warn_threshold: bool,
3613    },
3614}
3615
3616fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
3617    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3618
3619    let model = LanguageModelRegistry::read_global(cx).active_model()?;
3620    let token_count = context.read(cx).token_count()?;
3621    let max_token_count = model.max_token_count();
3622
3623    let remaining_tokens = max_token_count as isize - token_count as isize;
3624    let token_state = if remaining_tokens <= 0 {
3625        TokenState::NoTokensLeft {
3626            max_token_count,
3627            token_count,
3628        }
3629    } else {
3630        let over_warn_threshold =
3631            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3632        TokenState::HasMoreTokens {
3633            max_token_count,
3634            token_count,
3635            over_warn_threshold,
3636        }
3637    };
3638    Some(token_state)
3639}
3640
3641fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3642    let image_size = data
3643        .size(0)
3644        .map(|dimension| Pixels::from(u32::from(dimension)));
3645    let image_ratio = image_size.width / image_size.height;
3646    let bounds_ratio = max_size.width / max_size.height;
3647
3648    if image_size.width > max_size.width || image_size.height > max_size.height {
3649        if bounds_ratio > image_ratio {
3650            size(
3651                image_size.width * (max_size.height / image_size.height),
3652                max_size.height,
3653            )
3654        } else {
3655            size(
3656                max_size.width,
3657                image_size.height * (max_size.width / image_size.width),
3658            )
3659        }
3660    } else {
3661        size(image_size.width, image_size.height)
3662    }
3663}
3664
3665pub enum ConfigurationError {
3666    NoProvider,
3667    ProviderNotAuthenticated,
3668    ProviderPendingTermsAcceptance(Arc<dyn LanguageModelProvider>),
3669}
3670
3671fn configuration_error(cx: &App) -> Option<ConfigurationError> {
3672    let provider = LanguageModelRegistry::read_global(cx).active_provider();
3673    let is_authenticated = provider
3674        .as_ref()
3675        .map_or(false, |provider| provider.is_authenticated(cx));
3676
3677    if provider.is_some() && is_authenticated {
3678        return None;
3679    }
3680
3681    if provider.is_none() {
3682        return Some(ConfigurationError::NoProvider);
3683    }
3684
3685    if !is_authenticated {
3686        return Some(ConfigurationError::ProviderNotAuthenticated);
3687    }
3688
3689    None
3690}
3691
3692pub fn humanize_token_count(count: usize) -> String {
3693    match count {
3694        0..=999 => count.to_string(),
3695        1000..=9999 => {
3696            let thousands = count / 1000;
3697            let hundreds = (count % 1000 + 50) / 100;
3698            if hundreds == 0 {
3699                format!("{}k", thousands)
3700            } else if hundreds == 10 {
3701                format!("{}k", thousands + 1)
3702            } else {
3703                format!("{}.{}k", thousands, hundreds)
3704            }
3705        }
3706        1_000_000..=9_999_999 => {
3707            let millions = count / 1_000_000;
3708            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
3709            if hundred_thousands == 0 {
3710                format!("{}M", millions)
3711            } else if hundred_thousands == 10 {
3712                format!("{}M", millions + 1)
3713            } else {
3714                format!("{}.{}M", millions, hundred_thousands)
3715            }
3716        }
3717        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
3718        _ => format!("{}k", (count + 500) / 1000),
3719    }
3720}
3721
3722pub fn make_lsp_adapter_delegate(
3723    project: &Entity<Project>,
3724    cx: &mut App,
3725) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3726    project.update(cx, |project, cx| {
3727        // TODO: Find the right worktree.
3728        let Some(worktree) = project.worktrees(cx).next() else {
3729            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3730        };
3731        let http_client = project.client().http_client().clone();
3732        project.lsp_store().update(cx, |_, cx| {
3733            Ok(Some(LocalLspAdapterDelegate::new(
3734                project.languages().clone(),
3735                project.environment(),
3736                cx.weak_entity(),
3737                &worktree,
3738                http_client,
3739                project.fs().clone(),
3740                cx,
3741            ) as Arc<dyn LspAdapterDelegate>))
3742        })
3743    })
3744}
3745
3746#[cfg(test)]
3747mod tests {
3748    use super::*;
3749    use gpui::App;
3750    use language::Buffer;
3751    use unindent::Unindent;
3752
3753    #[gpui::test]
3754    fn test_find_code_blocks(cx: &mut App) {
3755        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3756
3757        let buffer = cx.new(|cx| {
3758            let text = r#"
3759                line 0
3760                line 1
3761                ```rust
3762                fn main() {}
3763                ```
3764                line 5
3765                line 6
3766                line 7
3767                ```go
3768                func main() {}
3769                ```
3770                line 11
3771                ```
3772                this is plain text code block
3773                ```
3774
3775                ```go
3776                func another() {}
3777                ```
3778                line 19
3779            "#
3780            .unindent();
3781            let mut buffer = Buffer::local(text, cx);
3782            buffer.set_language(Some(markdown.clone()), cx);
3783            buffer
3784        });
3785        let snapshot = buffer.read(cx).snapshot();
3786
3787        let code_blocks = vec![
3788            Point::new(3, 0)..Point::new(4, 0),
3789            Point::new(9, 0)..Point::new(10, 0),
3790            Point::new(13, 0)..Point::new(14, 0),
3791            Point::new(17, 0)..Point::new(18, 0),
3792        ]
3793        .into_iter()
3794        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3795        .collect::<Vec<_>>();
3796
3797        let expected_results = vec![
3798            (0, None),
3799            (1, None),
3800            (2, Some(code_blocks[0].clone())),
3801            (3, Some(code_blocks[0].clone())),
3802            (4, Some(code_blocks[0].clone())),
3803            (5, None),
3804            (6, None),
3805            (7, None),
3806            (8, Some(code_blocks[1].clone())),
3807            (9, Some(code_blocks[1].clone())),
3808            (10, Some(code_blocks[1].clone())),
3809            (11, None),
3810            (12, Some(code_blocks[2].clone())),
3811            (13, Some(code_blocks[2].clone())),
3812            (14, Some(code_blocks[2].clone())),
3813            (15, None),
3814            (16, Some(code_blocks[3].clone())),
3815            (17, Some(code_blocks[3].clone())),
3816            (18, Some(code_blocks[3].clone())),
3817            (19, None),
3818        ];
3819
3820        for (row, expected) in expected_results {
3821            let offset = snapshot.point_to_offset(Point::new(row, 0));
3822            let range = find_surrounding_code_block(&snapshot, offset);
3823            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3824        }
3825    }
3826}