context_editor.rs

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