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