context_editor.rs

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