context_editor.rs

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