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