assistant_panel.rs

   1use crate::{
   2    assistant_settings::{AssistantDockPosition, AssistantSettings},
   3    humanize_token_count,
   4    prompt_library::open_prompt_library,
   5    prompts::PromptBuilder,
   6    slash_command::{
   7        default_command::DefaultSlashCommand,
   8        docs_command::{DocsSlashCommand, DocsSlashCommandArgs},
   9        file_command::{self, codeblock_fence_for_path},
  10        SlashCommandCompletionProvider, SlashCommandRegistry,
  11    },
  12    slash_command_picker,
  13    terminal_inline_assistant::TerminalInlineAssistant,
  14    Assist, AssistantPatch, AssistantPatchStatus, CacheStatus, ConfirmCommand, Content, Context,
  15    ContextEvent, ContextId, ContextStore, ContextStoreEvent, CopyCode, CycleMessageRole,
  16    DeployHistory, DeployPromptLibrary, Edit, InlineAssistant, InsertDraggedFiles,
  17    InsertIntoEditor, Message, MessageId, MessageMetadata, MessageStatus, ModelPickerDelegate,
  18    ModelSelector, NewContext, PendingSlashCommand, PendingSlashCommandStatus, QuoteSelection,
  19    RemoteContextMetadata, RequestType, SavedContextMetadata, Split, ToggleFocus,
  20    ToggleModelSelector,
  21};
  22use anyhow::Result;
  23use assistant_slash_command::{SlashCommand, SlashCommandOutputSection};
  24use assistant_tool::ToolRegistry;
  25use client::{proto, zed_urls, Client, Status};
  26use collections::{BTreeSet, HashMap, HashSet};
  27use editor::{
  28    actions::{FoldAt, MoveToEndOfLine, Newline, ShowCompletions, UnfoldAt},
  29    display_map::{
  30        BlockContext, BlockId, BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata,
  31        CustomBlockId, FoldId, RenderBlock, ToDisplayPoint,
  32    },
  33    scroll::{Autoscroll, AutoscrollStrategy},
  34    Anchor, Editor, EditorEvent, ProposedChangeLocation, ProposedChangesEditor, RowExt,
  35    ToOffset as _, ToPoint,
  36};
  37use editor::{display_map::CreaseId, FoldPlaceholder};
  38use fs::Fs;
  39use futures::FutureExt;
  40use gpui::{
  41    canvas, div, img, percentage, point, pulsating_between, size, Action, Animation, AnimationExt,
  42    AnyElement, AnyView, AppContext, AsyncWindowContext, ClipboardEntry, ClipboardItem,
  43    CursorStyle, Empty, Entity, EventEmitter, ExternalPaths, FocusHandle, FocusableView,
  44    FontWeight, InteractiveElement, IntoElement, Model, ParentElement, Pixels, Render, RenderImage,
  45    SharedString, Size, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
  46    UpdateGlobal, View, VisualContext, WeakView, WindowContext,
  47};
  48use indexed_docs::IndexedDocsStore;
  49use language::{
  50    language_settings::SoftWrap, BufferSnapshot, LanguageRegistry, LspAdapterDelegate, ToOffset,
  51};
  52use language_model::{
  53    provider::cloud::PROVIDER_ID, LanguageModelProvider, LanguageModelProviderId,
  54    LanguageModelRegistry, Role,
  55};
  56use language_model::{LanguageModelImage, LanguageModelToolUse};
  57use multi_buffer::MultiBufferRow;
  58use picker::{Picker, PickerDelegate};
  59use project::lsp_store::LocalLspAdapterDelegate;
  60use project::{Project, Worktree};
  61use rope::Point;
  62use search::{buffer_search::DivRegistrar, BufferSearchBar};
  63use serde::{Deserialize, Serialize};
  64use settings::{update_settings_file, Settings};
  65use smol::stream::StreamExt;
  66use std::{
  67    borrow::Cow,
  68    cmp,
  69    ops::{ControlFlow, Range},
  70    path::PathBuf,
  71    sync::Arc,
  72    time::Duration,
  73};
  74use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
  75use text::SelectionGoal;
  76use ui::{
  77    prelude::*,
  78    utils::{format_distance_from_now, DateTimeType},
  79    Avatar, ButtonLike, ContextMenu, Disclosure, ElevationIndex, KeyBinding, ListItem,
  80    ListItemSpacing, PopoverMenu, PopoverMenuHandle, TintColor, Tooltip,
  81};
  82use util::{maybe, ResultExt};
  83use workspace::{
  84    dock::{DockPosition, Panel, PanelEvent},
  85    item::{self, FollowableItem, Item, ItemHandle},
  86    notifications::NotificationId,
  87    pane::{self, SaveIntent},
  88    searchable::{SearchEvent, SearchableItem},
  89    DraggedSelection, Pane, Save, ShowConfiguration, Toast, ToggleZoom, ToolbarItemEvent,
  90    ToolbarItemLocation, ToolbarItemView, Workspace,
  91};
  92use workspace::{searchable::SearchableItemHandle, DraggedTab};
  93use zed_actions::InlineAssist;
  94
  95pub fn init(cx: &mut AppContext) {
  96    workspace::FollowableViewRegistry::register::<ContextEditor>(cx);
  97    cx.observe_new_views(
  98        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  99            workspace
 100                .register_action(|workspace, _: &ToggleFocus, cx| {
 101                    let settings = AssistantSettings::get_global(cx);
 102                    if !settings.enabled {
 103                        return;
 104                    }
 105
 106                    workspace.toggle_panel_focus::<AssistantPanel>(cx);
 107                })
 108                .register_action(AssistantPanel::inline_assist)
 109                .register_action(ContextEditor::quote_selection)
 110                .register_action(ContextEditor::insert_selection)
 111                .register_action(ContextEditor::copy_code)
 112                .register_action(ContextEditor::insert_dragged_files)
 113                .register_action(AssistantPanel::show_configuration)
 114                .register_action(AssistantPanel::create_new_context);
 115        },
 116    )
 117    .detach();
 118
 119    cx.observe_new_views(
 120        |terminal_panel: &mut TerminalPanel, cx: &mut ViewContext<TerminalPanel>| {
 121            let settings = AssistantSettings::get_global(cx);
 122            terminal_panel.asssistant_enabled(settings.enabled, cx);
 123        },
 124    )
 125    .detach();
 126}
 127
 128pub enum AssistantPanelEvent {
 129    ContextEdited,
 130}
 131
 132pub struct AssistantPanel {
 133    pane: View<Pane>,
 134    workspace: WeakView<Workspace>,
 135    width: Option<Pixels>,
 136    height: Option<Pixels>,
 137    project: Model<Project>,
 138    context_store: Model<ContextStore>,
 139    languages: Arc<LanguageRegistry>,
 140    fs: Arc<dyn Fs>,
 141    subscriptions: Vec<Subscription>,
 142    model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
 143    model_summary_editor: View<Editor>,
 144    authenticate_provider_task: Option<(LanguageModelProviderId, Task<()>)>,
 145    configuration_subscription: Option<Subscription>,
 146    client_status: Option<client::Status>,
 147    watch_client_status: Option<Task<()>>,
 148    show_zed_ai_notice: bool,
 149}
 150
 151#[derive(Clone)]
 152enum ContextMetadata {
 153    Remote(RemoteContextMetadata),
 154    Saved(SavedContextMetadata),
 155}
 156
 157struct SavedContextPickerDelegate {
 158    store: Model<ContextStore>,
 159    project: Model<Project>,
 160    matches: Vec<ContextMetadata>,
 161    selected_index: usize,
 162}
 163
 164enum SavedContextPickerEvent {
 165    Confirmed(ContextMetadata),
 166}
 167
 168enum InlineAssistTarget {
 169    Editor(View<Editor>, bool),
 170    Terminal(View<TerminalView>),
 171}
 172
 173impl EventEmitter<SavedContextPickerEvent> for Picker<SavedContextPickerDelegate> {}
 174
 175impl SavedContextPickerDelegate {
 176    fn new(project: Model<Project>, store: Model<ContextStore>) -> Self {
 177        Self {
 178            project,
 179            store,
 180            matches: Vec::new(),
 181            selected_index: 0,
 182        }
 183    }
 184}
 185
 186impl PickerDelegate for SavedContextPickerDelegate {
 187    type ListItem = ListItem;
 188
 189    fn match_count(&self) -> usize {
 190        self.matches.len()
 191    }
 192
 193    fn selected_index(&self) -> usize {
 194        self.selected_index
 195    }
 196
 197    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
 198        self.selected_index = ix;
 199    }
 200
 201    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
 202        "Search...".into()
 203    }
 204
 205    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
 206        let search = self.store.read(cx).search(query, cx);
 207        cx.spawn(|this, mut cx| async move {
 208            let matches = search.await;
 209            this.update(&mut cx, |this, cx| {
 210                let host_contexts = this.delegate.store.read(cx).host_contexts();
 211                this.delegate.matches = host_contexts
 212                    .iter()
 213                    .cloned()
 214                    .map(ContextMetadata::Remote)
 215                    .chain(matches.into_iter().map(ContextMetadata::Saved))
 216                    .collect();
 217                this.delegate.selected_index = 0;
 218                cx.notify();
 219            })
 220            .ok();
 221        })
 222    }
 223
 224    fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
 225        if let Some(metadata) = self.matches.get(self.selected_index) {
 226            cx.emit(SavedContextPickerEvent::Confirmed(metadata.clone()));
 227        }
 228    }
 229
 230    fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
 231
 232    fn render_match(
 233        &self,
 234        ix: usize,
 235        selected: bool,
 236        cx: &mut ViewContext<Picker<Self>>,
 237    ) -> Option<Self::ListItem> {
 238        let context = self.matches.get(ix)?;
 239        let item = match context {
 240            ContextMetadata::Remote(context) => {
 241                let host_user = self.project.read(cx).host().and_then(|collaborator| {
 242                    self.project
 243                        .read(cx)
 244                        .user_store()
 245                        .read(cx)
 246                        .get_cached_user(collaborator.user_id)
 247                });
 248                div()
 249                    .flex()
 250                    .w_full()
 251                    .justify_between()
 252                    .gap_2()
 253                    .child(
 254                        h_flex().flex_1().overflow_x_hidden().child(
 255                            Label::new(context.summary.clone().unwrap_or(DEFAULT_TAB_TITLE.into()))
 256                                .size(LabelSize::Small),
 257                        ),
 258                    )
 259                    .child(
 260                        h_flex()
 261                            .gap_2()
 262                            .children(if let Some(host_user) = host_user {
 263                                vec![
 264                                    Avatar::new(host_user.avatar_uri.clone()).into_any_element(),
 265                                    Label::new(format!("Shared by @{}", host_user.github_login))
 266                                        .color(Color::Muted)
 267                                        .size(LabelSize::Small)
 268                                        .into_any_element(),
 269                                ]
 270                            } else {
 271                                vec![Label::new("Shared by host")
 272                                    .color(Color::Muted)
 273                                    .size(LabelSize::Small)
 274                                    .into_any_element()]
 275                            }),
 276                    )
 277            }
 278            ContextMetadata::Saved(context) => div()
 279                .flex()
 280                .w_full()
 281                .justify_between()
 282                .gap_2()
 283                .child(
 284                    h_flex()
 285                        .flex_1()
 286                        .child(Label::new(context.title.clone()).size(LabelSize::Small))
 287                        .overflow_x_hidden(),
 288                )
 289                .child(
 290                    Label::new(format_distance_from_now(
 291                        DateTimeType::Local(context.mtime),
 292                        false,
 293                        true,
 294                        true,
 295                    ))
 296                    .color(Color::Muted)
 297                    .size(LabelSize::Small),
 298                ),
 299        };
 300        Some(
 301            ListItem::new(ix)
 302                .inset(true)
 303                .spacing(ListItemSpacing::Sparse)
 304                .selected(selected)
 305                .child(item),
 306        )
 307    }
 308}
 309
 310impl AssistantPanel {
 311    pub fn load(
 312        workspace: WeakView<Workspace>,
 313        prompt_builder: Arc<PromptBuilder>,
 314        cx: AsyncWindowContext,
 315    ) -> Task<Result<View<Self>>> {
 316        cx.spawn(|mut cx| async move {
 317            let context_store = workspace
 318                .update(&mut cx, |workspace, cx| {
 319                    let project = workspace.project().clone();
 320                    ContextStore::new(project, prompt_builder.clone(), cx)
 321                })?
 322                .await?;
 323
 324            workspace.update(&mut cx, |workspace, cx| {
 325                // TODO: deserialize state.
 326                cx.new_view(|cx| Self::new(workspace, context_store, cx))
 327            })
 328        })
 329    }
 330
 331    fn new(
 332        workspace: &Workspace,
 333        context_store: Model<ContextStore>,
 334        cx: &mut ViewContext<Self>,
 335    ) -> Self {
 336        let model_selector_menu_handle = PopoverMenuHandle::default();
 337        let model_summary_editor = cx.new_view(Editor::single_line);
 338        let context_editor_toolbar = cx.new_view(|_| {
 339            ContextEditorToolbarItem::new(
 340                workspace,
 341                model_selector_menu_handle.clone(),
 342                model_summary_editor.clone(),
 343            )
 344        });
 345
 346        let pane = cx.new_view(|cx| {
 347            let mut pane = Pane::new(
 348                workspace.weak_handle(),
 349                workspace.project().clone(),
 350                Default::default(),
 351                None,
 352                NewContext.boxed_clone(),
 353                cx,
 354            );
 355
 356            let project = workspace.project().clone();
 357            pane.set_custom_drop_handle(cx, move |_, dropped_item, cx| {
 358                let action = maybe!({
 359                    if project.read(cx).is_local() {
 360                        if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
 361                            return Some(InsertDraggedFiles::ExternalFiles(paths.paths().to_vec()));
 362                        }
 363                    }
 364
 365                    let project_paths = if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>()
 366                    {
 367                        if &tab.pane == cx.view() {
 368                            return None;
 369                        }
 370                        let item = tab.pane.read(cx).item_for_index(tab.ix);
 371                        Some(
 372                            item.and_then(|item| item.project_path(cx))
 373                                .into_iter()
 374                                .collect::<Vec<_>>(),
 375                        )
 376                    } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>()
 377                    {
 378                        Some(
 379                            selection
 380                                .items()
 381                                .filter_map(|item| {
 382                                    project.read(cx).path_for_entry(item.entry_id, cx)
 383                                })
 384                                .collect::<Vec<_>>(),
 385                        )
 386                    } else {
 387                        None
 388                    }?;
 389
 390                    let paths = project_paths
 391                        .into_iter()
 392                        .filter_map(|project_path| {
 393                            let worktree = project
 394                                .read(cx)
 395                                .worktree_for_id(project_path.worktree_id, cx)?;
 396
 397                            let mut full_path = PathBuf::from(worktree.read(cx).root_name());
 398                            full_path.push(&project_path.path);
 399                            Some(full_path)
 400                        })
 401                        .collect::<Vec<_>>();
 402
 403                    Some(InsertDraggedFiles::ProjectPaths(paths))
 404                });
 405
 406                if let Some(action) = action {
 407                    cx.dispatch_action(action.boxed_clone());
 408                }
 409
 410                ControlFlow::Break(())
 411            });
 412
 413            pane.set_can_split(false, cx);
 414            pane.set_can_navigate(true, cx);
 415            pane.display_nav_history_buttons(None);
 416            pane.set_should_display_tab_bar(|_| true);
 417            pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
 418                let focus_handle = pane.focus_handle(cx);
 419                let left_children = IconButton::new("history", IconName::HistoryRerun)
 420                    .icon_size(IconSize::Small)
 421                    .on_click(cx.listener({
 422                        let focus_handle = focus_handle.clone();
 423                        move |_, _, cx| {
 424                            focus_handle.focus(cx);
 425                            cx.dispatch_action(DeployHistory.boxed_clone())
 426                        }
 427                    }))
 428                    .tooltip({
 429                        let focus_handle = focus_handle.clone();
 430                        move |cx| {
 431                            Tooltip::for_action_in(
 432                                "Open History",
 433                                &DeployHistory,
 434                                &focus_handle,
 435                                cx,
 436                            )
 437                        }
 438                    })
 439                    .selected(
 440                        pane.active_item()
 441                            .map_or(false, |item| item.downcast::<ContextHistory>().is_some()),
 442                    );
 443                let _pane = cx.view().clone();
 444                let right_children = h_flex()
 445                    .gap(Spacing::Small.rems(cx))
 446                    .child(
 447                        IconButton::new("new-context", IconName::Plus)
 448                            .on_click(
 449                                cx.listener(|_, _, cx| {
 450                                    cx.dispatch_action(NewContext.boxed_clone())
 451                                }),
 452                            )
 453                            .tooltip(move |cx| {
 454                                Tooltip::for_action_in(
 455                                    "New Context",
 456                                    &NewContext,
 457                                    &focus_handle,
 458                                    cx,
 459                                )
 460                            }),
 461                    )
 462                    .child(
 463                        PopoverMenu::new("assistant-panel-popover-menu")
 464                            .trigger(
 465                                IconButton::new("menu", IconName::Menu).icon_size(IconSize::Small),
 466                            )
 467                            .menu(move |cx| {
 468                                let zoom_label = if _pane.read(cx).is_zoomed() {
 469                                    "Zoom Out"
 470                                } else {
 471                                    "Zoom In"
 472                                };
 473                                let focus_handle = _pane.focus_handle(cx);
 474                                Some(ContextMenu::build(cx, move |menu, _| {
 475                                    menu.context(focus_handle.clone())
 476                                        .action("New Context", Box::new(NewContext))
 477                                        .action("History", Box::new(DeployHistory))
 478                                        .action("Prompt Library", Box::new(DeployPromptLibrary))
 479                                        .action("Configure", Box::new(ShowConfiguration))
 480                                        .action(zoom_label, Box::new(ToggleZoom))
 481                                }))
 482                            }),
 483                    )
 484                    .into_any_element()
 485                    .into();
 486
 487                (Some(left_children.into_any_element()), right_children)
 488            });
 489            pane.toolbar().update(cx, |toolbar, cx| {
 490                toolbar.add_item(context_editor_toolbar.clone(), cx);
 491                toolbar.add_item(cx.new_view(BufferSearchBar::new), cx)
 492            });
 493            pane
 494        });
 495
 496        let subscriptions = vec![
 497            cx.observe(&pane, |_, _, cx| cx.notify()),
 498            cx.subscribe(&pane, Self::handle_pane_event),
 499            cx.subscribe(&context_editor_toolbar, Self::handle_toolbar_event),
 500            cx.subscribe(&model_summary_editor, Self::handle_summary_editor_event),
 501            cx.subscribe(&context_store, Self::handle_context_store_event),
 502            cx.subscribe(
 503                &LanguageModelRegistry::global(cx),
 504                |this, _, event: &language_model::Event, cx| match event {
 505                    language_model::Event::ActiveModelChanged => {
 506                        this.completion_provider_changed(cx);
 507                    }
 508                    language_model::Event::ProviderStateChanged => {
 509                        this.ensure_authenticated(cx);
 510                        cx.notify()
 511                    }
 512                    language_model::Event::AddedProvider(_)
 513                    | language_model::Event::RemovedProvider(_) => {
 514                        this.ensure_authenticated(cx);
 515                    }
 516                },
 517            ),
 518        ];
 519
 520        let watch_client_status = Self::watch_client_status(workspace.client().clone(), cx);
 521
 522        let mut this = Self {
 523            pane,
 524            workspace: workspace.weak_handle(),
 525            width: None,
 526            height: None,
 527            project: workspace.project().clone(),
 528            context_store,
 529            languages: workspace.app_state().languages.clone(),
 530            fs: workspace.app_state().fs.clone(),
 531            subscriptions,
 532            model_selector_menu_handle,
 533            model_summary_editor,
 534            authenticate_provider_task: None,
 535            configuration_subscription: None,
 536            client_status: None,
 537            watch_client_status: Some(watch_client_status),
 538            show_zed_ai_notice: false,
 539        };
 540        this.new_context(cx);
 541        this
 542    }
 543
 544    fn watch_client_status(client: Arc<Client>, cx: &mut ViewContext<Self>) -> Task<()> {
 545        let mut status_rx = client.status();
 546
 547        cx.spawn(|this, mut cx| async move {
 548            while let Some(status) = status_rx.next().await {
 549                this.update(&mut cx, |this, cx| {
 550                    if this.client_status.is_none()
 551                        || this
 552                            .client_status
 553                            .map_or(false, |old_status| old_status != status)
 554                    {
 555                        this.update_zed_ai_notice_visibility(status, cx);
 556                    }
 557                    this.client_status = Some(status);
 558                })
 559                .log_err();
 560            }
 561            this.update(&mut cx, |this, _cx| this.watch_client_status = None)
 562                .log_err();
 563        })
 564    }
 565
 566    fn handle_pane_event(
 567        &mut self,
 568        pane: View<Pane>,
 569        event: &pane::Event,
 570        cx: &mut ViewContext<Self>,
 571    ) {
 572        let update_model_summary = match event {
 573            pane::Event::Remove { .. } => {
 574                cx.emit(PanelEvent::Close);
 575                false
 576            }
 577            pane::Event::ZoomIn => {
 578                cx.emit(PanelEvent::ZoomIn);
 579                false
 580            }
 581            pane::Event::ZoomOut => {
 582                cx.emit(PanelEvent::ZoomOut);
 583                false
 584            }
 585
 586            pane::Event::AddItem { item } => {
 587                self.workspace
 588                    .update(cx, |workspace, cx| {
 589                        item.added_to_pane(workspace, self.pane.clone(), cx)
 590                    })
 591                    .ok();
 592                true
 593            }
 594
 595            pane::Event::ActivateItem { local } => {
 596                if *local {
 597                    self.workspace
 598                        .update(cx, |workspace, cx| {
 599                            workspace.unfollow_in_pane(&pane, cx);
 600                        })
 601                        .ok();
 602                }
 603                cx.emit(AssistantPanelEvent::ContextEdited);
 604                true
 605            }
 606            pane::Event::RemovedItem { .. } => {
 607                let has_configuration_view = self
 608                    .pane
 609                    .read(cx)
 610                    .items_of_type::<ConfigurationView>()
 611                    .next()
 612                    .is_some();
 613
 614                if !has_configuration_view {
 615                    self.configuration_subscription = None;
 616                }
 617
 618                cx.emit(AssistantPanelEvent::ContextEdited);
 619                true
 620            }
 621
 622            _ => false,
 623        };
 624
 625        if update_model_summary {
 626            if let Some(editor) = self.active_context_editor(cx) {
 627                self.show_updated_summary(&editor, cx)
 628            }
 629        }
 630    }
 631
 632    fn handle_summary_editor_event(
 633        &mut self,
 634        model_summary_editor: View<Editor>,
 635        event: &EditorEvent,
 636        cx: &mut ViewContext<Self>,
 637    ) {
 638        if matches!(event, EditorEvent::Edited { .. }) {
 639            if let Some(context_editor) = self.active_context_editor(cx) {
 640                let new_summary = model_summary_editor.read(cx).text(cx);
 641                context_editor.update(cx, |context_editor, cx| {
 642                    context_editor.context.update(cx, |context, cx| {
 643                        if context.summary().is_none()
 644                            && (new_summary == DEFAULT_TAB_TITLE || new_summary.trim().is_empty())
 645                        {
 646                            return;
 647                        }
 648                        context.custom_summary(new_summary, cx)
 649                    });
 650                });
 651            }
 652        }
 653    }
 654
 655    fn update_zed_ai_notice_visibility(
 656        &mut self,
 657        client_status: Status,
 658        cx: &mut ViewContext<Self>,
 659    ) {
 660        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
 661
 662        // If we're signed out and don't have a provider configured, or we're signed-out AND Zed.dev is
 663        // the provider, we want to show a nudge to sign in.
 664        let show_zed_ai_notice = client_status.is_signed_out()
 665            && active_provider.map_or(true, |provider| provider.id().0 == PROVIDER_ID);
 666
 667        self.show_zed_ai_notice = show_zed_ai_notice;
 668        cx.notify();
 669    }
 670
 671    fn handle_toolbar_event(
 672        &mut self,
 673        _: View<ContextEditorToolbarItem>,
 674        _: &ContextEditorToolbarItemEvent,
 675        cx: &mut ViewContext<Self>,
 676    ) {
 677        if let Some(context_editor) = self.active_context_editor(cx) {
 678            context_editor.update(cx, |context_editor, cx| {
 679                context_editor.context.update(cx, |context, cx| {
 680                    context.summarize(true, cx);
 681                })
 682            })
 683        }
 684    }
 685
 686    fn handle_context_store_event(
 687        &mut self,
 688        _context_store: Model<ContextStore>,
 689        event: &ContextStoreEvent,
 690        cx: &mut ViewContext<Self>,
 691    ) {
 692        let ContextStoreEvent::ContextCreated(context_id) = event;
 693        let Some(context) = self
 694            .context_store
 695            .read(cx)
 696            .loaded_context_for_id(&context_id, cx)
 697        else {
 698            log::error!("no context found with ID: {}", context_id.to_proto());
 699            return;
 700        };
 701        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
 702            .log_err()
 703            .flatten();
 704
 705        let assistant_panel = cx.view().downgrade();
 706        let editor = cx.new_view(|cx| {
 707            let mut editor = ContextEditor::for_context(
 708                context,
 709                self.fs.clone(),
 710                self.workspace.clone(),
 711                self.project.clone(),
 712                lsp_adapter_delegate,
 713                assistant_panel,
 714                cx,
 715            );
 716            editor.insert_default_prompt(cx);
 717            editor
 718        });
 719
 720        self.show_context(editor.clone(), cx);
 721    }
 722
 723    fn completion_provider_changed(&mut self, cx: &mut ViewContext<Self>) {
 724        if let Some(editor) = self.active_context_editor(cx) {
 725            editor.update(cx, |active_context, cx| {
 726                active_context
 727                    .context
 728                    .update(cx, |context, cx| context.completion_provider_changed(cx))
 729            })
 730        }
 731
 732        let Some(new_provider_id) = LanguageModelRegistry::read_global(cx)
 733            .active_provider()
 734            .map(|p| p.id())
 735        else {
 736            return;
 737        };
 738
 739        if self
 740            .authenticate_provider_task
 741            .as_ref()
 742            .map_or(true, |(old_provider_id, _)| {
 743                *old_provider_id != new_provider_id
 744            })
 745        {
 746            self.authenticate_provider_task = None;
 747            self.ensure_authenticated(cx);
 748        }
 749
 750        if let Some(status) = self.client_status {
 751            self.update_zed_ai_notice_visibility(status, cx);
 752        }
 753    }
 754
 755    fn ensure_authenticated(&mut self, cx: &mut ViewContext<Self>) {
 756        if self.is_authenticated(cx) {
 757            return;
 758        }
 759
 760        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
 761            return;
 762        };
 763
 764        let load_credentials = self.authenticate(cx);
 765
 766        if self.authenticate_provider_task.is_none() {
 767            self.authenticate_provider_task = Some((
 768                provider.id(),
 769                cx.spawn(|this, mut cx| async move {
 770                    if let Some(future) = load_credentials {
 771                        let _ = future.await;
 772                    }
 773                    this.update(&mut cx, |this, _cx| {
 774                        this.authenticate_provider_task = None;
 775                    })
 776                    .log_err();
 777                }),
 778            ));
 779        }
 780    }
 781
 782    pub fn inline_assist(
 783        workspace: &mut Workspace,
 784        action: &InlineAssist,
 785        cx: &mut ViewContext<Workspace>,
 786    ) {
 787        let settings = AssistantSettings::get_global(cx);
 788        if !settings.enabled {
 789            return;
 790        }
 791
 792        let Some(assistant_panel) = workspace.panel::<AssistantPanel>(cx) else {
 793            return;
 794        };
 795
 796        let Some(inline_assist_target) =
 797            Self::resolve_inline_assist_target(workspace, &assistant_panel, cx)
 798        else {
 799            return;
 800        };
 801
 802        let initial_prompt = action.prompt.clone();
 803
 804        if assistant_panel.update(cx, |assistant, cx| assistant.is_authenticated(cx)) {
 805            match inline_assist_target {
 806                InlineAssistTarget::Editor(active_editor, include_context) => {
 807                    InlineAssistant::update_global(cx, |assistant, cx| {
 808                        assistant.assist(
 809                            &active_editor,
 810                            Some(cx.view().downgrade()),
 811                            include_context.then_some(&assistant_panel),
 812                            initial_prompt,
 813                            cx,
 814                        )
 815                    })
 816                }
 817                InlineAssistTarget::Terminal(active_terminal) => {
 818                    TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 819                        assistant.assist(
 820                            &active_terminal,
 821                            Some(cx.view().downgrade()),
 822                            Some(&assistant_panel),
 823                            initial_prompt,
 824                            cx,
 825                        )
 826                    })
 827                }
 828            }
 829        } else {
 830            let assistant_panel = assistant_panel.downgrade();
 831            cx.spawn(|workspace, mut cx| async move {
 832                let Some(task) =
 833                    assistant_panel.update(&mut cx, |assistant, cx| assistant.authenticate(cx))?
 834                else {
 835                    let answer = cx
 836                        .prompt(
 837                            gpui::PromptLevel::Warning,
 838                            "No language model provider configured",
 839                            None,
 840                            &["Configure", "Cancel"],
 841                        )
 842                        .await
 843                        .ok();
 844                    if let Some(answer) = answer {
 845                        if answer == 0 {
 846                            cx.update(|cx| cx.dispatch_action(Box::new(ShowConfiguration)))
 847                                .ok();
 848                        }
 849                    }
 850                    return Ok(());
 851                };
 852                task.await?;
 853                if assistant_panel.update(&mut cx, |panel, cx| panel.is_authenticated(cx))? {
 854                    cx.update(|cx| match inline_assist_target {
 855                        InlineAssistTarget::Editor(active_editor, include_context) => {
 856                            let assistant_panel = if include_context {
 857                                assistant_panel.upgrade()
 858                            } else {
 859                                None
 860                            };
 861                            InlineAssistant::update_global(cx, |assistant, cx| {
 862                                assistant.assist(
 863                                    &active_editor,
 864                                    Some(workspace),
 865                                    assistant_panel.as_ref(),
 866                                    initial_prompt,
 867                                    cx,
 868                                )
 869                            })
 870                        }
 871                        InlineAssistTarget::Terminal(active_terminal) => {
 872                            TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 873                                assistant.assist(
 874                                    &active_terminal,
 875                                    Some(workspace),
 876                                    assistant_panel.upgrade().as_ref(),
 877                                    initial_prompt,
 878                                    cx,
 879                                )
 880                            })
 881                        }
 882                    })?
 883                } else {
 884                    workspace.update(&mut cx, |workspace, cx| {
 885                        workspace.focus_panel::<AssistantPanel>(cx)
 886                    })?;
 887                }
 888
 889                anyhow::Ok(())
 890            })
 891            .detach_and_log_err(cx)
 892        }
 893    }
 894
 895    fn resolve_inline_assist_target(
 896        workspace: &mut Workspace,
 897        assistant_panel: &View<AssistantPanel>,
 898        cx: &mut WindowContext,
 899    ) -> Option<InlineAssistTarget> {
 900        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
 901            if terminal_panel
 902                .read(cx)
 903                .focus_handle(cx)
 904                .contains_focused(cx)
 905            {
 906                if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
 907                    pane.read(cx)
 908                        .active_item()
 909                        .and_then(|t| t.downcast::<TerminalView>())
 910                }) {
 911                    return Some(InlineAssistTarget::Terminal(terminal_view));
 912                }
 913            }
 914        }
 915        let context_editor =
 916            assistant_panel
 917                .read(cx)
 918                .active_context_editor(cx)
 919                .and_then(|editor| {
 920                    let editor = &editor.read(cx).editor;
 921                    if editor.read(cx).is_focused(cx) {
 922                        Some(editor.clone())
 923                    } else {
 924                        None
 925                    }
 926                });
 927
 928        if let Some(context_editor) = context_editor {
 929            Some(InlineAssistTarget::Editor(context_editor, false))
 930        } else if let Some(workspace_editor) = workspace
 931            .active_item(cx)
 932            .and_then(|item| item.act_as::<Editor>(cx))
 933        {
 934            Some(InlineAssistTarget::Editor(workspace_editor, true))
 935        } else if let Some(terminal_view) = workspace
 936            .active_item(cx)
 937            .and_then(|item| item.act_as::<TerminalView>(cx))
 938        {
 939            Some(InlineAssistTarget::Terminal(terminal_view))
 940        } else {
 941            None
 942        }
 943    }
 944
 945    pub fn create_new_context(
 946        workspace: &mut Workspace,
 947        _: &NewContext,
 948        cx: &mut ViewContext<Workspace>,
 949    ) {
 950        if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
 951            let did_create_context = panel
 952                .update(cx, |panel, cx| {
 953                    panel.new_context(cx)?;
 954
 955                    Some(())
 956                })
 957                .is_some();
 958            if did_create_context {
 959                ContextEditor::quote_selection(workspace, &Default::default(), cx);
 960            }
 961        }
 962    }
 963
 964    fn new_context(&mut self, cx: &mut ViewContext<Self>) -> Option<View<ContextEditor>> {
 965        let project = self.project.read(cx);
 966        if project.is_via_collab() {
 967            let task = self
 968                .context_store
 969                .update(cx, |store, cx| store.create_remote_context(cx));
 970
 971            cx.spawn(|this, mut cx| async move {
 972                let context = task.await?;
 973
 974                this.update(&mut cx, |this, cx| {
 975                    let workspace = this.workspace.clone();
 976                    let project = this.project.clone();
 977                    let lsp_adapter_delegate =
 978                        make_lsp_adapter_delegate(&project, cx).log_err().flatten();
 979
 980                    let fs = this.fs.clone();
 981                    let project = this.project.clone();
 982                    let weak_assistant_panel = cx.view().downgrade();
 983
 984                    let editor = cx.new_view(|cx| {
 985                        ContextEditor::for_context(
 986                            context,
 987                            fs,
 988                            workspace,
 989                            project,
 990                            lsp_adapter_delegate,
 991                            weak_assistant_panel,
 992                            cx,
 993                        )
 994                    });
 995
 996                    this.show_context(editor, cx);
 997
 998                    anyhow::Ok(())
 999                })??;
1000
1001                anyhow::Ok(())
1002            })
1003            .detach_and_log_err(cx);
1004
1005            None
1006        } else {
1007            let context = self.context_store.update(cx, |store, cx| store.create(cx));
1008            let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
1009                .log_err()
1010                .flatten();
1011
1012            let assistant_panel = cx.view().downgrade();
1013            let editor = cx.new_view(|cx| {
1014                let mut editor = ContextEditor::for_context(
1015                    context,
1016                    self.fs.clone(),
1017                    self.workspace.clone(),
1018                    self.project.clone(),
1019                    lsp_adapter_delegate,
1020                    assistant_panel,
1021                    cx,
1022                );
1023                editor.insert_default_prompt(cx);
1024                editor
1025            });
1026
1027            self.show_context(editor.clone(), cx);
1028            let workspace = self.workspace.clone();
1029            cx.spawn(move |_, mut cx| async move {
1030                workspace
1031                    .update(&mut cx, |workspace, cx| {
1032                        workspace.focus_panel::<AssistantPanel>(cx);
1033                    })
1034                    .ok();
1035            })
1036            .detach();
1037            Some(editor)
1038        }
1039    }
1040
1041    fn show_context(&mut self, context_editor: View<ContextEditor>, cx: &mut ViewContext<Self>) {
1042        let focus = self.focus_handle(cx).contains_focused(cx);
1043        let prev_len = self.pane.read(cx).items_len();
1044        self.pane.update(cx, |pane, cx| {
1045            pane.add_item(Box::new(context_editor.clone()), focus, focus, None, cx)
1046        });
1047
1048        if prev_len != self.pane.read(cx).items_len() {
1049            self.subscriptions
1050                .push(cx.subscribe(&context_editor, Self::handle_context_editor_event));
1051        }
1052
1053        self.show_updated_summary(&context_editor, cx);
1054
1055        cx.emit(AssistantPanelEvent::ContextEdited);
1056        cx.notify();
1057    }
1058
1059    fn show_updated_summary(
1060        &self,
1061        context_editor: &View<ContextEditor>,
1062        cx: &mut ViewContext<Self>,
1063    ) {
1064        context_editor.update(cx, |context_editor, cx| {
1065            let new_summary = context_editor.title(cx).to_string();
1066            self.model_summary_editor.update(cx, |summary_editor, cx| {
1067                if summary_editor.text(cx) != new_summary {
1068                    summary_editor.set_text(new_summary, cx);
1069                }
1070            });
1071        });
1072    }
1073
1074    fn handle_context_editor_event(
1075        &mut self,
1076        context_editor: View<ContextEditor>,
1077        event: &EditorEvent,
1078        cx: &mut ViewContext<Self>,
1079    ) {
1080        match event {
1081            EditorEvent::TitleChanged => {
1082                self.show_updated_summary(&context_editor, cx);
1083                cx.notify()
1084            }
1085            EditorEvent::Edited { .. } => cx.emit(AssistantPanelEvent::ContextEdited),
1086            _ => {}
1087        }
1088    }
1089
1090    fn show_configuration(
1091        workspace: &mut Workspace,
1092        _: &ShowConfiguration,
1093        cx: &mut ViewContext<Workspace>,
1094    ) {
1095        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1096            return;
1097        };
1098
1099        if !panel.focus_handle(cx).contains_focused(cx) {
1100            workspace.toggle_panel_focus::<AssistantPanel>(cx);
1101        }
1102
1103        panel.update(cx, |this, cx| {
1104            this.show_configuration_tab(cx);
1105        })
1106    }
1107
1108    fn show_configuration_tab(&mut self, cx: &mut ViewContext<Self>) {
1109        let configuration_item_ix = self
1110            .pane
1111            .read(cx)
1112            .items()
1113            .position(|item| item.downcast::<ConfigurationView>().is_some());
1114
1115        if let Some(configuration_item_ix) = configuration_item_ix {
1116            self.pane.update(cx, |pane, cx| {
1117                pane.activate_item(configuration_item_ix, true, true, cx);
1118            });
1119        } else {
1120            let configuration = cx.new_view(ConfigurationView::new);
1121            self.configuration_subscription = Some(cx.subscribe(
1122                &configuration,
1123                |this, _, event: &ConfigurationViewEvent, cx| match event {
1124                    ConfigurationViewEvent::NewProviderContextEditor(provider) => {
1125                        if LanguageModelRegistry::read_global(cx)
1126                            .active_provider()
1127                            .map_or(true, |p| p.id() != provider.id())
1128                        {
1129                            if let Some(model) = provider.provided_models(cx).first().cloned() {
1130                                update_settings_file::<AssistantSettings>(
1131                                    this.fs.clone(),
1132                                    cx,
1133                                    move |settings, _| settings.set_model(model),
1134                                );
1135                            }
1136                        }
1137
1138                        this.new_context(cx);
1139                    }
1140                },
1141            ));
1142            self.pane.update(cx, |pane, cx| {
1143                pane.add_item(Box::new(configuration), true, true, None, cx);
1144            });
1145        }
1146    }
1147
1148    fn deploy_history(&mut self, _: &DeployHistory, cx: &mut ViewContext<Self>) {
1149        let history_item_ix = self
1150            .pane
1151            .read(cx)
1152            .items()
1153            .position(|item| item.downcast::<ContextHistory>().is_some());
1154
1155        if let Some(history_item_ix) = history_item_ix {
1156            self.pane.update(cx, |pane, cx| {
1157                pane.activate_item(history_item_ix, true, true, cx);
1158            });
1159        } else {
1160            let assistant_panel = cx.view().downgrade();
1161            let history = cx.new_view(|cx| {
1162                ContextHistory::new(
1163                    self.project.clone(),
1164                    self.context_store.clone(),
1165                    assistant_panel,
1166                    cx,
1167                )
1168            });
1169            self.pane.update(cx, |pane, cx| {
1170                pane.add_item(Box::new(history), true, true, None, cx);
1171            });
1172        }
1173    }
1174
1175    fn deploy_prompt_library(&mut self, _: &DeployPromptLibrary, cx: &mut ViewContext<Self>) {
1176        open_prompt_library(self.languages.clone(), cx).detach_and_log_err(cx);
1177    }
1178
1179    fn toggle_model_selector(&mut self, _: &ToggleModelSelector, cx: &mut ViewContext<Self>) {
1180        self.model_selector_menu_handle.toggle(cx);
1181    }
1182
1183    fn active_context_editor(&self, cx: &AppContext) -> Option<View<ContextEditor>> {
1184        self.pane
1185            .read(cx)
1186            .active_item()?
1187            .downcast::<ContextEditor>()
1188    }
1189
1190    pub fn active_context(&self, cx: &AppContext) -> Option<Model<Context>> {
1191        Some(self.active_context_editor(cx)?.read(cx).context.clone())
1192    }
1193
1194    fn open_saved_context(
1195        &mut self,
1196        path: PathBuf,
1197        cx: &mut ViewContext<Self>,
1198    ) -> Task<Result<()>> {
1199        let existing_context = self.pane.read(cx).items().find_map(|item| {
1200            item.downcast::<ContextEditor>()
1201                .filter(|editor| editor.read(cx).context.read(cx).path() == Some(&path))
1202        });
1203        if let Some(existing_context) = existing_context {
1204            return cx.spawn(|this, mut cx| async move {
1205                this.update(&mut cx, |this, cx| this.show_context(existing_context, cx))
1206            });
1207        }
1208
1209        let context = self
1210            .context_store
1211            .update(cx, |store, cx| store.open_local_context(path.clone(), cx));
1212        let fs = self.fs.clone();
1213        let project = self.project.clone();
1214        let workspace = self.workspace.clone();
1215
1216        let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err().flatten();
1217
1218        cx.spawn(|this, mut cx| async move {
1219            let context = context.await?;
1220            let assistant_panel = this.clone();
1221            this.update(&mut cx, |this, cx| {
1222                let editor = cx.new_view(|cx| {
1223                    ContextEditor::for_context(
1224                        context,
1225                        fs,
1226                        workspace,
1227                        project,
1228                        lsp_adapter_delegate,
1229                        assistant_panel,
1230                        cx,
1231                    )
1232                });
1233                this.show_context(editor, cx);
1234                anyhow::Ok(())
1235            })??;
1236            Ok(())
1237        })
1238    }
1239
1240    fn open_remote_context(
1241        &mut self,
1242        id: ContextId,
1243        cx: &mut ViewContext<Self>,
1244    ) -> Task<Result<View<ContextEditor>>> {
1245        let existing_context = self.pane.read(cx).items().find_map(|item| {
1246            item.downcast::<ContextEditor>()
1247                .filter(|editor| *editor.read(cx).context.read(cx).id() == id)
1248        });
1249        if let Some(existing_context) = existing_context {
1250            return cx.spawn(|this, mut cx| async move {
1251                this.update(&mut cx, |this, cx| {
1252                    this.show_context(existing_context.clone(), cx)
1253                })?;
1254                Ok(existing_context)
1255            });
1256        }
1257
1258        let context = self
1259            .context_store
1260            .update(cx, |store, cx| store.open_remote_context(id, cx));
1261        let fs = self.fs.clone();
1262        let workspace = self.workspace.clone();
1263        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
1264            .log_err()
1265            .flatten();
1266
1267        cx.spawn(|this, mut cx| async move {
1268            let context = context.await?;
1269            let assistant_panel = this.clone();
1270            this.update(&mut cx, |this, cx| {
1271                let editor = cx.new_view(|cx| {
1272                    ContextEditor::for_context(
1273                        context,
1274                        fs,
1275                        workspace,
1276                        this.project.clone(),
1277                        lsp_adapter_delegate,
1278                        assistant_panel,
1279                        cx,
1280                    )
1281                });
1282                this.show_context(editor.clone(), cx);
1283                anyhow::Ok(editor)
1284            })?
1285        })
1286    }
1287
1288    fn is_authenticated(&mut self, cx: &mut ViewContext<Self>) -> bool {
1289        LanguageModelRegistry::read_global(cx)
1290            .active_provider()
1291            .map_or(false, |provider| provider.is_authenticated(cx))
1292    }
1293
1294    fn authenticate(&mut self, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
1295        LanguageModelRegistry::read_global(cx)
1296            .active_provider()
1297            .map_or(None, |provider| Some(provider.authenticate(cx)))
1298    }
1299}
1300
1301impl Render for AssistantPanel {
1302    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1303        let mut registrar = DivRegistrar::new(
1304            |panel, cx| {
1305                panel
1306                    .pane
1307                    .read(cx)
1308                    .toolbar()
1309                    .read(cx)
1310                    .item_of_type::<BufferSearchBar>()
1311            },
1312            cx,
1313        );
1314        BufferSearchBar::register(&mut registrar);
1315        let registrar = registrar.into_div();
1316
1317        v_flex()
1318            .key_context("AssistantPanel")
1319            .size_full()
1320            .on_action(cx.listener(|this, _: &NewContext, cx| {
1321                this.new_context(cx);
1322            }))
1323            .on_action(
1324                cx.listener(|this, _: &ShowConfiguration, cx| this.show_configuration_tab(cx)),
1325            )
1326            .on_action(cx.listener(AssistantPanel::deploy_history))
1327            .on_action(cx.listener(AssistantPanel::deploy_prompt_library))
1328            .on_action(cx.listener(AssistantPanel::toggle_model_selector))
1329            .child(registrar.size_full().child(self.pane.clone()))
1330            .into_any_element()
1331    }
1332}
1333
1334impl Panel for AssistantPanel {
1335    fn persistent_name() -> &'static str {
1336        "AssistantPanel"
1337    }
1338
1339    fn position(&self, cx: &WindowContext) -> DockPosition {
1340        match AssistantSettings::get_global(cx).dock {
1341            AssistantDockPosition::Left => DockPosition::Left,
1342            AssistantDockPosition::Bottom => DockPosition::Bottom,
1343            AssistantDockPosition::Right => DockPosition::Right,
1344        }
1345    }
1346
1347    fn position_is_valid(&self, _: DockPosition) -> bool {
1348        true
1349    }
1350
1351    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1352        settings::update_settings_file::<AssistantSettings>(
1353            self.fs.clone(),
1354            cx,
1355            move |settings, _| {
1356                let dock = match position {
1357                    DockPosition::Left => AssistantDockPosition::Left,
1358                    DockPosition::Bottom => AssistantDockPosition::Bottom,
1359                    DockPosition::Right => AssistantDockPosition::Right,
1360                };
1361                settings.set_dock(dock);
1362            },
1363        );
1364    }
1365
1366    fn size(&self, cx: &WindowContext) -> Pixels {
1367        let settings = AssistantSettings::get_global(cx);
1368        match self.position(cx) {
1369            DockPosition::Left | DockPosition::Right => {
1370                self.width.unwrap_or(settings.default_width)
1371            }
1372            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1373        }
1374    }
1375
1376    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1377        match self.position(cx) {
1378            DockPosition::Left | DockPosition::Right => self.width = size,
1379            DockPosition::Bottom => self.height = size,
1380        }
1381        cx.notify();
1382    }
1383
1384    fn is_zoomed(&self, cx: &WindowContext) -> bool {
1385        self.pane.read(cx).is_zoomed()
1386    }
1387
1388    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1389        self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
1390    }
1391
1392    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1393        if active {
1394            if self.pane.read(cx).items_len() == 0 {
1395                self.new_context(cx);
1396            }
1397
1398            self.ensure_authenticated(cx);
1399        }
1400    }
1401
1402    fn pane(&self) -> Option<View<Pane>> {
1403        Some(self.pane.clone())
1404    }
1405
1406    fn remote_id() -> Option<proto::PanelId> {
1407        Some(proto::PanelId::AssistantPanel)
1408    }
1409
1410    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
1411        let settings = AssistantSettings::get_global(cx);
1412        if !settings.enabled || !settings.button {
1413            return None;
1414        }
1415
1416        Some(IconName::ZedAssistant)
1417    }
1418
1419    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1420        Some("Assistant Panel")
1421    }
1422
1423    fn toggle_action(&self) -> Box<dyn Action> {
1424        Box::new(ToggleFocus)
1425    }
1426}
1427
1428impl EventEmitter<PanelEvent> for AssistantPanel {}
1429impl EventEmitter<AssistantPanelEvent> for AssistantPanel {}
1430
1431impl FocusableView for AssistantPanel {
1432    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1433        self.pane.focus_handle(cx)
1434    }
1435}
1436
1437pub enum ContextEditorEvent {
1438    Edited,
1439    TabContentChanged,
1440}
1441
1442#[derive(Copy, Clone, Debug, PartialEq)]
1443struct ScrollPosition {
1444    offset_before_cursor: gpui::Point<f32>,
1445    cursor: Anchor,
1446}
1447
1448struct PatchViewState {
1449    footer_block_id: CustomBlockId,
1450    crease_id: CreaseId,
1451    editor: Option<PatchEditorState>,
1452    update_task: Option<Task<()>>,
1453}
1454
1455struct PatchEditorState {
1456    editor: WeakView<ProposedChangesEditor>,
1457    opened_patch: AssistantPatch,
1458}
1459
1460type MessageHeader = MessageMetadata;
1461
1462#[derive(Clone)]
1463enum AssistError {
1464    FileRequired,
1465    PaymentRequired,
1466    MaxMonthlySpendReached,
1467    Message(SharedString),
1468}
1469
1470pub struct ContextEditor {
1471    context: Model<Context>,
1472    fs: Arc<dyn Fs>,
1473    workspace: WeakView<Workspace>,
1474    project: Model<Project>,
1475    lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1476    editor: View<Editor>,
1477    blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
1478    image_blocks: HashSet<CustomBlockId>,
1479    scroll_position: Option<ScrollPosition>,
1480    remote_id: Option<workspace::ViewId>,
1481    pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
1482    pending_slash_command_blocks: HashMap<Range<language::Anchor>, CustomBlockId>,
1483    pending_tool_use_creases: HashMap<Range<language::Anchor>, CreaseId>,
1484    _subscriptions: Vec<Subscription>,
1485    patches: HashMap<Range<language::Anchor>, PatchViewState>,
1486    active_patch: Option<Range<language::Anchor>>,
1487    assistant_panel: WeakView<AssistantPanel>,
1488    last_error: Option<AssistError>,
1489    show_accept_terms: bool,
1490    pub(crate) slash_menu_handle:
1491        PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
1492    // dragged_file_worktrees is used to keep references to worktrees that were added
1493    // when the user drag/dropped an external file onto the context editor. Since
1494    // the worktree is not part of the project panel, it would be dropped as soon as
1495    // the file is opened. In order to keep the worktree alive for the duration of the
1496    // context editor, we keep a reference here.
1497    dragged_file_worktrees: Vec<Model<Worktree>>,
1498}
1499
1500const DEFAULT_TAB_TITLE: &str = "New Context";
1501const MAX_TAB_TITLE_LEN: usize = 16;
1502
1503impl ContextEditor {
1504    fn for_context(
1505        context: Model<Context>,
1506        fs: Arc<dyn Fs>,
1507        workspace: WeakView<Workspace>,
1508        project: Model<Project>,
1509        lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1510        assistant_panel: WeakView<AssistantPanel>,
1511        cx: &mut ViewContext<Self>,
1512    ) -> Self {
1513        let completion_provider = SlashCommandCompletionProvider::new(
1514            Some(cx.view().downgrade()),
1515            Some(workspace.clone()),
1516        );
1517
1518        let editor = cx.new_view(|cx| {
1519            let mut editor = Editor::for_buffer(context.read(cx).buffer().clone(), None, cx);
1520            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
1521            editor.set_show_line_numbers(false, cx);
1522            editor.set_show_git_diff_gutter(false, cx);
1523            editor.set_show_code_actions(false, cx);
1524            editor.set_show_runnables(false, cx);
1525            editor.set_show_wrap_guides(false, cx);
1526            editor.set_show_indent_guides(false, cx);
1527            editor.set_completion_provider(Some(Box::new(completion_provider)));
1528            editor.set_collaboration_hub(Box::new(project.clone()));
1529            editor
1530        });
1531
1532        let _subscriptions = vec![
1533            cx.observe(&context, |_, _, cx| cx.notify()),
1534            cx.subscribe(&context, Self::handle_context_event),
1535            cx.subscribe(&editor, Self::handle_editor_event),
1536            cx.subscribe(&editor, Self::handle_editor_search_event),
1537        ];
1538
1539        let sections = context.read(cx).slash_command_output_sections().to_vec();
1540        let patch_ranges = context.read(cx).patch_ranges().collect::<Vec<_>>();
1541        let mut this = Self {
1542            context,
1543            editor,
1544            lsp_adapter_delegate,
1545            blocks: Default::default(),
1546            image_blocks: Default::default(),
1547            scroll_position: None,
1548            remote_id: None,
1549            fs,
1550            workspace,
1551            project,
1552            pending_slash_command_creases: HashMap::default(),
1553            pending_slash_command_blocks: HashMap::default(),
1554            pending_tool_use_creases: HashMap::default(),
1555            _subscriptions,
1556            patches: HashMap::default(),
1557            active_patch: None,
1558            assistant_panel,
1559            last_error: None,
1560            show_accept_terms: false,
1561            slash_menu_handle: Default::default(),
1562            dragged_file_worktrees: Vec::new(),
1563        };
1564        this.update_message_headers(cx);
1565        this.update_image_blocks(cx);
1566        this.insert_slash_command_output_sections(sections, false, cx);
1567        this.patches_updated(&Vec::new(), &patch_ranges, cx);
1568        this
1569    }
1570
1571    fn insert_default_prompt(&mut self, cx: &mut ViewContext<Self>) {
1572        let command_name = DefaultSlashCommand.name();
1573        self.editor.update(cx, |editor, cx| {
1574            editor.insert(&format!("/{command_name}\n\n"), cx)
1575        });
1576        let command = self.context.update(cx, |context, cx| {
1577            context.reparse(cx);
1578            context.pending_slash_commands()[0].clone()
1579        });
1580        self.run_command(
1581            command.source_range,
1582            &command.name,
1583            &command.arguments,
1584            false,
1585            false,
1586            self.workspace.clone(),
1587            cx,
1588        );
1589    }
1590
1591    fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
1592        self.send_to_model(RequestType::Chat, cx);
1593    }
1594
1595    fn edit(&mut self, _: &Edit, cx: &mut ViewContext<Self>) {
1596        self.send_to_model(RequestType::SuggestEdits, cx);
1597    }
1598
1599    fn focus_active_patch(&mut self, cx: &mut ViewContext<Self>) -> bool {
1600        if let Some((_range, patch)) = self.active_patch() {
1601            if let Some(editor) = patch
1602                .editor
1603                .as_ref()
1604                .and_then(|state| state.editor.upgrade())
1605            {
1606                cx.focus_view(&editor);
1607                return true;
1608            }
1609        }
1610
1611        false
1612    }
1613
1614    fn send_to_model(&mut self, request_type: RequestType, cx: &mut ViewContext<Self>) {
1615        let provider = LanguageModelRegistry::read_global(cx).active_provider();
1616        if provider
1617            .as_ref()
1618            .map_or(false, |provider| provider.must_accept_terms(cx))
1619        {
1620            self.show_accept_terms = true;
1621            cx.notify();
1622            return;
1623        }
1624
1625        if self.focus_active_patch(cx) {
1626            return;
1627        }
1628
1629        self.last_error = None;
1630
1631        if request_type == RequestType::SuggestEdits && !self.context.read(cx).contains_files(cx) {
1632            self.last_error = Some(AssistError::FileRequired);
1633            cx.notify();
1634        } else if let Some(user_message) = self
1635            .context
1636            .update(cx, |context, cx| context.assist(request_type, cx))
1637        {
1638            let new_selection = {
1639                let cursor = user_message
1640                    .start
1641                    .to_offset(self.context.read(cx).buffer().read(cx));
1642                cursor..cursor
1643            };
1644            self.editor.update(cx, |editor, cx| {
1645                editor.change_selections(
1646                    Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
1647                    cx,
1648                    |selections| selections.select_ranges([new_selection]),
1649                );
1650            });
1651            // Avoid scrolling to the new cursor position so the assistant's output is stable.
1652            cx.defer(|this, _| this.scroll_position = None);
1653        }
1654
1655        cx.notify();
1656    }
1657
1658    fn cancel(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1659        self.last_error = None;
1660
1661        if self
1662            .context
1663            .update(cx, |context, cx| context.cancel_last_assist(cx))
1664        {
1665            return;
1666        }
1667
1668        cx.propagate();
1669    }
1670
1671    fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
1672        let cursors = self.cursors(cx);
1673        self.context.update(cx, |context, cx| {
1674            let messages = context
1675                .messages_for_offsets(cursors, cx)
1676                .into_iter()
1677                .map(|message| message.id)
1678                .collect();
1679            context.cycle_message_roles(messages, cx)
1680        });
1681    }
1682
1683    fn cursors(&self, cx: &mut WindowContext) -> Vec<usize> {
1684        let selections = self
1685            .editor
1686            .update(cx, |editor, cx| editor.selections.all::<usize>(cx));
1687        selections
1688            .into_iter()
1689            .map(|selection| selection.head())
1690            .collect()
1691    }
1692
1693    pub fn insert_command(&mut self, name: &str, cx: &mut ViewContext<Self>) {
1694        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1695            self.editor.update(cx, |editor, cx| {
1696                editor.transact(cx, |editor, cx| {
1697                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel());
1698                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1699                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
1700                    if newest_cursor.column > 0
1701                        || snapshot
1702                            .chars_at(newest_cursor)
1703                            .next()
1704                            .map_or(false, |ch| ch != '\n')
1705                    {
1706                        editor.move_to_end_of_line(
1707                            &MoveToEndOfLine {
1708                                stop_at_soft_wraps: false,
1709                            },
1710                            cx,
1711                        );
1712                        editor.newline(&Newline, cx);
1713                    }
1714
1715                    editor.insert(&format!("/{name}"), cx);
1716                    if command.accepts_arguments() {
1717                        editor.insert(" ", cx);
1718                        editor.show_completions(&ShowCompletions::default(), cx);
1719                    }
1720                });
1721            });
1722            if !command.requires_argument() {
1723                self.confirm_command(&ConfirmCommand, cx);
1724            }
1725        }
1726    }
1727
1728    pub fn confirm_command(&mut self, _: &ConfirmCommand, cx: &mut ViewContext<Self>) {
1729        if self.editor.read(cx).has_active_completions_menu() {
1730            return;
1731        }
1732
1733        let selections = self.editor.read(cx).selections.disjoint_anchors();
1734        let mut commands_by_range = HashMap::default();
1735        let workspace = self.workspace.clone();
1736        self.context.update(cx, |context, cx| {
1737            context.reparse(cx);
1738            for selection in selections.iter() {
1739                if let Some(command) =
1740                    context.pending_command_for_position(selection.head().text_anchor, cx)
1741                {
1742                    commands_by_range
1743                        .entry(command.source_range.clone())
1744                        .or_insert_with(|| command.clone());
1745                }
1746            }
1747        });
1748
1749        if commands_by_range.is_empty() {
1750            cx.propagate();
1751        } else {
1752            for command in commands_by_range.into_values() {
1753                self.run_command(
1754                    command.source_range,
1755                    &command.name,
1756                    &command.arguments,
1757                    true,
1758                    false,
1759                    workspace.clone(),
1760                    cx,
1761                );
1762            }
1763            cx.stop_propagation();
1764        }
1765    }
1766
1767    #[allow(clippy::too_many_arguments)]
1768    pub fn run_command(
1769        &mut self,
1770        command_range: Range<language::Anchor>,
1771        name: &str,
1772        arguments: &[String],
1773        ensure_trailing_newline: bool,
1774        expand_result: bool,
1775        workspace: WeakView<Workspace>,
1776        cx: &mut ViewContext<Self>,
1777    ) {
1778        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1779            let context = self.context.read(cx);
1780            let sections = context
1781                .slash_command_output_sections()
1782                .into_iter()
1783                .filter(|section| section.is_valid(context.buffer().read(cx)))
1784                .cloned()
1785                .collect::<Vec<_>>();
1786            let snapshot = context.buffer().read(cx).snapshot();
1787            let output = command.run(
1788                arguments,
1789                &sections,
1790                snapshot,
1791                workspace,
1792                self.lsp_adapter_delegate.clone(),
1793                cx,
1794            );
1795            self.context.update(cx, |context, cx| {
1796                context.insert_command_output(
1797                    command_range,
1798                    output,
1799                    ensure_trailing_newline,
1800                    expand_result,
1801                    cx,
1802                )
1803            });
1804        }
1805    }
1806
1807    fn handle_context_event(
1808        &mut self,
1809        _: Model<Context>,
1810        event: &ContextEvent,
1811        cx: &mut ViewContext<Self>,
1812    ) {
1813        let context_editor = cx.view().downgrade();
1814
1815        match event {
1816            ContextEvent::MessagesEdited => {
1817                self.update_message_headers(cx);
1818                self.update_image_blocks(cx);
1819                self.context.update(cx, |context, cx| {
1820                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1821                });
1822            }
1823            ContextEvent::SummaryChanged => {
1824                cx.emit(EditorEvent::TitleChanged);
1825                self.context.update(cx, |context, cx| {
1826                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1827                });
1828            }
1829            ContextEvent::StreamedCompletion => {
1830                self.editor.update(cx, |editor, cx| {
1831                    if let Some(scroll_position) = self.scroll_position {
1832                        let snapshot = editor.snapshot(cx);
1833                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
1834                        let scroll_top =
1835                            cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
1836                        editor.set_scroll_position(
1837                            point(scroll_position.offset_before_cursor.x, scroll_top),
1838                            cx,
1839                        );
1840                    }
1841
1842                    let new_tool_uses = self
1843                        .context
1844                        .read(cx)
1845                        .pending_tool_uses()
1846                        .into_iter()
1847                        .filter(|tool_use| {
1848                            !self
1849                                .pending_tool_use_creases
1850                                .contains_key(&tool_use.source_range)
1851                        })
1852                        .cloned()
1853                        .collect::<Vec<_>>();
1854
1855                    let buffer = editor.buffer().read(cx).snapshot(cx);
1856                    let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
1857                    let excerpt_id = *excerpt_id;
1858
1859                    let mut buffer_rows_to_fold = BTreeSet::new();
1860
1861                    let creases = new_tool_uses
1862                        .iter()
1863                        .map(|tool_use| {
1864                            let placeholder = FoldPlaceholder {
1865                                render: render_fold_icon_button(
1866                                    cx.view().downgrade(),
1867                                    IconName::PocketKnife,
1868                                    tool_use.name.clone().into(),
1869                                ),
1870                                constrain_width: false,
1871                                merge_adjacent: false,
1872                            };
1873                            let render_trailer =
1874                                move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
1875
1876                            let start = buffer
1877                                .anchor_in_excerpt(excerpt_id, tool_use.source_range.start)
1878                                .unwrap();
1879                            let end = buffer
1880                                .anchor_in_excerpt(excerpt_id, tool_use.source_range.end)
1881                                .unwrap();
1882
1883                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1884                            buffer_rows_to_fold.insert(buffer_row);
1885
1886                            self.context.update(cx, |context, cx| {
1887                                context.insert_content(
1888                                    Content::ToolUse {
1889                                        range: tool_use.source_range.clone(),
1890                                        tool_use: LanguageModelToolUse {
1891                                            id: tool_use.id.to_string(),
1892                                            name: tool_use.name.clone(),
1893                                            input: tool_use.input.clone(),
1894                                        },
1895                                    },
1896                                    cx,
1897                                );
1898                            });
1899
1900                            Crease::new(
1901                                start..end,
1902                                placeholder,
1903                                fold_toggle("tool-use"),
1904                                render_trailer,
1905                            )
1906                        })
1907                        .collect::<Vec<_>>();
1908
1909                    let crease_ids = editor.insert_creases(creases, cx);
1910
1911                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1912                        editor.fold_at(&FoldAt { buffer_row }, cx);
1913                    }
1914
1915                    self.pending_tool_use_creases.extend(
1916                        new_tool_uses
1917                            .iter()
1918                            .map(|tool_use| tool_use.source_range.clone())
1919                            .zip(crease_ids),
1920                    );
1921                });
1922            }
1923            ContextEvent::PatchesUpdated { removed, updated } => {
1924                self.patches_updated(removed, updated, cx);
1925            }
1926            ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
1927                self.editor.update(cx, |editor, cx| {
1928                    let buffer = editor.buffer().read(cx).snapshot(cx);
1929                    let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
1930                    let excerpt_id = *excerpt_id;
1931
1932                    editor.remove_creases(
1933                        removed
1934                            .iter()
1935                            .filter_map(|range| self.pending_slash_command_creases.remove(range)),
1936                        cx,
1937                    );
1938
1939                    editor.remove_blocks(
1940                        HashSet::from_iter(
1941                            removed.iter().filter_map(|range| {
1942                                self.pending_slash_command_blocks.remove(range)
1943                            }),
1944                        ),
1945                        None,
1946                        cx,
1947                    );
1948
1949                    let crease_ids = editor.insert_creases(
1950                        updated.iter().map(|command| {
1951                            let workspace = self.workspace.clone();
1952                            let confirm_command = Arc::new({
1953                                let context_editor = context_editor.clone();
1954                                let command = command.clone();
1955                                move |cx: &mut WindowContext| {
1956                                    context_editor
1957                                        .update(cx, |context_editor, cx| {
1958                                            context_editor.run_command(
1959                                                command.source_range.clone(),
1960                                                &command.name,
1961                                                &command.arguments,
1962                                                false,
1963                                                false,
1964                                                workspace.clone(),
1965                                                cx,
1966                                            );
1967                                        })
1968                                        .ok();
1969                                }
1970                            });
1971                            let placeholder = FoldPlaceholder {
1972                                render: Arc::new(move |_, _, _| Empty.into_any()),
1973                                constrain_width: false,
1974                                merge_adjacent: false,
1975                            };
1976                            let render_toggle = {
1977                                let confirm_command = confirm_command.clone();
1978                                let command = command.clone();
1979                                move |row, _, _, _cx: &mut WindowContext| {
1980                                    render_pending_slash_command_gutter_decoration(
1981                                        row,
1982                                        &command.status,
1983                                        confirm_command.clone(),
1984                                    )
1985                                }
1986                            };
1987                            let render_trailer = {
1988                                let command = command.clone();
1989                                move |row, _unfold, cx: &mut WindowContext| {
1990                                    // TODO: In the future we should investigate how we can expose
1991                                    // this as a hook on the `SlashCommand` trait so that we don't
1992                                    // need to special-case it here.
1993                                    if command.name == DocsSlashCommand::NAME {
1994                                        return render_docs_slash_command_trailer(
1995                                            row,
1996                                            command.clone(),
1997                                            cx,
1998                                        );
1999                                    }
2000
2001                                    Empty.into_any()
2002                                }
2003                            };
2004
2005                            let start = buffer
2006                                .anchor_in_excerpt(excerpt_id, command.source_range.start)
2007                                .unwrap();
2008                            let end = buffer
2009                                .anchor_in_excerpt(excerpt_id, command.source_range.end)
2010                                .unwrap();
2011                            Crease::new(start..end, placeholder, render_toggle, render_trailer)
2012                        }),
2013                        cx,
2014                    );
2015
2016                    let block_ids = editor.insert_blocks(
2017                        updated
2018                            .iter()
2019                            .filter_map(|command| match &command.status {
2020                                PendingSlashCommandStatus::Error(error) => {
2021                                    Some((command, error.clone()))
2022                                }
2023                                _ => None,
2024                            })
2025                            .map(|(command, error_message)| BlockProperties {
2026                                style: BlockStyle::Fixed,
2027                                height: 1,
2028                                placement: BlockPlacement::Below(Anchor {
2029                                    buffer_id: Some(buffer_id),
2030                                    excerpt_id,
2031                                    text_anchor: command.source_range.start,
2032                                }),
2033                                render: slash_command_error_block_renderer(error_message),
2034                                priority: 0,
2035                            }),
2036                        None,
2037                        cx,
2038                    );
2039
2040                    self.pending_slash_command_creases.extend(
2041                        updated
2042                            .iter()
2043                            .map(|command| command.source_range.clone())
2044                            .zip(crease_ids),
2045                    );
2046
2047                    self.pending_slash_command_blocks.extend(
2048                        updated
2049                            .iter()
2050                            .map(|command| command.source_range.clone())
2051                            .zip(block_ids),
2052                    );
2053                })
2054            }
2055            ContextEvent::SlashCommandFinished {
2056                output_range,
2057                sections,
2058                run_commands_in_output,
2059                expand_result,
2060            } => {
2061                self.insert_slash_command_output_sections(
2062                    sections.iter().cloned(),
2063                    *expand_result,
2064                    cx,
2065                );
2066
2067                if *run_commands_in_output {
2068                    let commands = self.context.update(cx, |context, cx| {
2069                        context.reparse(cx);
2070                        context
2071                            .pending_commands_for_range(output_range.clone(), cx)
2072                            .to_vec()
2073                    });
2074
2075                    for command in commands {
2076                        self.run_command(
2077                            command.source_range,
2078                            &command.name,
2079                            &command.arguments,
2080                            false,
2081                            false,
2082                            self.workspace.clone(),
2083                            cx,
2084                        );
2085                    }
2086                }
2087            }
2088            ContextEvent::UsePendingTools => {
2089                let pending_tool_uses = self
2090                    .context
2091                    .read(cx)
2092                    .pending_tool_uses()
2093                    .into_iter()
2094                    .filter(|tool_use| tool_use.status.is_idle())
2095                    .cloned()
2096                    .collect::<Vec<_>>();
2097
2098                for tool_use in pending_tool_uses {
2099                    let tool_registry = ToolRegistry::global(cx);
2100                    if let Some(tool) = tool_registry.tool(&tool_use.name) {
2101                        let task = tool.run(tool_use.input, self.workspace.clone(), cx);
2102
2103                        self.context.update(cx, |context, cx| {
2104                            context.insert_tool_output(tool_use.id.clone(), task, cx);
2105                        });
2106                    }
2107                }
2108            }
2109            ContextEvent::ToolFinished {
2110                tool_use_id,
2111                output_range,
2112            } => {
2113                self.editor.update(cx, |editor, cx| {
2114                    let buffer = editor.buffer().read(cx).snapshot(cx);
2115                    let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
2116                    let excerpt_id = *excerpt_id;
2117
2118                    let placeholder = FoldPlaceholder {
2119                        render: render_fold_icon_button(
2120                            cx.view().downgrade(),
2121                            IconName::PocketKnife,
2122                            format!("Tool Result: {tool_use_id}").into(),
2123                        ),
2124                        constrain_width: false,
2125                        merge_adjacent: false,
2126                    };
2127                    let render_trailer =
2128                        move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
2129
2130                    let start = buffer
2131                        .anchor_in_excerpt(excerpt_id, output_range.start)
2132                        .unwrap();
2133                    let end = buffer
2134                        .anchor_in_excerpt(excerpt_id, output_range.end)
2135                        .unwrap();
2136
2137                    let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2138
2139                    let crease = Crease::new(
2140                        start..end,
2141                        placeholder,
2142                        fold_toggle("tool-use"),
2143                        render_trailer,
2144                    );
2145
2146                    editor.insert_creases([crease], cx);
2147                    editor.fold_at(&FoldAt { buffer_row }, cx);
2148                });
2149            }
2150            ContextEvent::Operation(_) => {}
2151            ContextEvent::ShowAssistError(error_message) => {
2152                self.last_error = Some(AssistError::Message(error_message.clone()));
2153            }
2154            ContextEvent::ShowPaymentRequiredError => {
2155                self.last_error = Some(AssistError::PaymentRequired);
2156            }
2157            ContextEvent::ShowMaxMonthlySpendReachedError => {
2158                self.last_error = Some(AssistError::MaxMonthlySpendReached);
2159            }
2160        }
2161    }
2162
2163    fn patches_updated(
2164        &mut self,
2165        removed: &Vec<Range<text::Anchor>>,
2166        updated: &Vec<Range<text::Anchor>>,
2167        cx: &mut ViewContext<ContextEditor>,
2168    ) {
2169        let this = cx.view().downgrade();
2170        let mut removed_crease_ids = Vec::new();
2171        let mut removed_block_ids = HashSet::default();
2172        let mut editors_to_close = Vec::new();
2173        for range in removed {
2174            if let Some(state) = self.patches.remove(range) {
2175                editors_to_close.extend(state.editor.and_then(|state| state.editor.upgrade()));
2176                removed_block_ids.insert(state.footer_block_id);
2177                removed_crease_ids.push(state.crease_id);
2178            }
2179        }
2180
2181        self.editor.update(cx, |editor, cx| {
2182            let snapshot = editor.snapshot(cx);
2183            let multibuffer = &snapshot.buffer_snapshot;
2184            let (&excerpt_id, _, _) = multibuffer.as_singleton().unwrap();
2185
2186            let mut replaced_blocks = HashMap::default();
2187            for range in updated {
2188                let Some(patch) = self.context.read(cx).patch_for_range(&range, cx).cloned() else {
2189                    continue;
2190                };
2191
2192                let path_count = patch.path_count();
2193                let patch_start = multibuffer
2194                    .anchor_in_excerpt(excerpt_id, patch.range.start)
2195                    .unwrap();
2196                let patch_end = multibuffer
2197                    .anchor_in_excerpt(excerpt_id, patch.range.end)
2198                    .unwrap();
2199                let render_block: RenderBlock = Box::new({
2200                    let this = this.clone();
2201                    let patch_range = range.clone();
2202                    move |cx: &mut BlockContext<'_, '_>| {
2203                        let max_width = cx.max_width;
2204                        let gutter_width = cx.gutter_dimensions.full_width();
2205                        let block_id = cx.block_id;
2206                        this.update(&mut **cx, |this, cx| {
2207                            this.render_patch_footer(
2208                                patch_range.clone(),
2209                                max_width,
2210                                gutter_width,
2211                                block_id,
2212                                cx,
2213                            )
2214                        })
2215                        .ok()
2216                        .flatten()
2217                        .unwrap_or_else(|| Empty.into_any())
2218                    }
2219                });
2220
2221                let header_placeholder = FoldPlaceholder {
2222                    render: {
2223                        let this = this.clone();
2224                        let patch_range = range.clone();
2225                        Arc::new(move |fold_id, _range, cx| {
2226                            this.update(cx, |this, cx| {
2227                                this.render_patch_header(patch_range.clone(), fold_id, cx)
2228                            })
2229                            .ok()
2230                            .flatten()
2231                            .unwrap_or_else(|| Empty.into_any())
2232                        })
2233                    },
2234                    constrain_width: false,
2235                    merge_adjacent: false,
2236                };
2237
2238                let should_refold;
2239                if let Some(state) = self.patches.get_mut(&range) {
2240                    replaced_blocks.insert(state.footer_block_id, render_block);
2241                    if let Some(editor_state) = &state.editor {
2242                        if editor_state.opened_patch != patch {
2243                            state.update_task = Some({
2244                                let this = this.clone();
2245                                cx.spawn(|_, cx| async move {
2246                                    Self::update_patch_editor(this.clone(), patch, cx)
2247                                        .await
2248                                        .log_err();
2249                                })
2250                            });
2251                        }
2252                    }
2253
2254                    should_refold =
2255                        snapshot.intersects_fold(patch_start.to_offset(&snapshot.buffer_snapshot));
2256                } else {
2257                    let block_ids = editor.insert_blocks(
2258                        [BlockProperties {
2259                            height: path_count as u32 + 1,
2260                            style: BlockStyle::Flex,
2261                            render: render_block,
2262                            placement: BlockPlacement::Below(patch_start),
2263                            priority: 0,
2264                        }],
2265                        None,
2266                        cx,
2267                    );
2268
2269                    let new_crease_ids = editor.insert_creases(
2270                        [Crease::new(
2271                            patch_start..patch_end,
2272                            header_placeholder.clone(),
2273                            fold_toggle("patch-header"),
2274                            |_, _, _| Empty.into_any_element(),
2275                        )],
2276                        cx,
2277                    );
2278
2279                    self.patches.insert(
2280                        range.clone(),
2281                        PatchViewState {
2282                            footer_block_id: block_ids[0],
2283                            crease_id: new_crease_ids[0],
2284                            editor: None,
2285                            update_task: None,
2286                        },
2287                    );
2288
2289                    should_refold = true;
2290                }
2291
2292                if should_refold {
2293                    editor.unfold_ranges([patch_start..patch_end], true, false, cx);
2294                    editor.fold_ranges([(patch_start..patch_end, header_placeholder)], false, cx);
2295                }
2296            }
2297
2298            editor.remove_creases(removed_crease_ids, cx);
2299            editor.remove_blocks(removed_block_ids, None, cx);
2300            editor.replace_blocks(replaced_blocks, None, cx);
2301        });
2302
2303        for editor in editors_to_close {
2304            self.close_patch_editor(editor, cx);
2305        }
2306
2307        self.update_active_patch(cx);
2308    }
2309
2310    fn insert_slash_command_output_sections(
2311        &mut self,
2312        sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
2313        expand_result: bool,
2314        cx: &mut ViewContext<Self>,
2315    ) {
2316        self.editor.update(cx, |editor, cx| {
2317            let buffer = editor.buffer().read(cx).snapshot(cx);
2318            let excerpt_id = *buffer.as_singleton().unwrap().0;
2319            let mut buffer_rows_to_fold = BTreeSet::new();
2320            let mut creases = Vec::new();
2321            for section in sections {
2322                let start = buffer
2323                    .anchor_in_excerpt(excerpt_id, section.range.start)
2324                    .unwrap();
2325                let end = buffer
2326                    .anchor_in_excerpt(excerpt_id, section.range.end)
2327                    .unwrap();
2328                let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2329                buffer_rows_to_fold.insert(buffer_row);
2330                creases.push(
2331                    Crease::new(
2332                        start..end,
2333                        FoldPlaceholder {
2334                            render: render_fold_icon_button(
2335                                cx.view().downgrade(),
2336                                section.icon,
2337                                section.label.clone(),
2338                            ),
2339                            constrain_width: false,
2340                            merge_adjacent: false,
2341                        },
2342                        render_slash_command_output_toggle,
2343                        |_, _, _| Empty.into_any_element(),
2344                    )
2345                    .with_metadata(CreaseMetadata {
2346                        icon: section.icon,
2347                        label: section.label,
2348                    }),
2349                );
2350            }
2351
2352            editor.insert_creases(creases, cx);
2353
2354            if expand_result {
2355                buffer_rows_to_fold.clear();
2356            }
2357            for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2358                editor.fold_at(&FoldAt { buffer_row }, cx);
2359            }
2360        });
2361    }
2362
2363    fn handle_editor_event(
2364        &mut self,
2365        _: View<Editor>,
2366        event: &EditorEvent,
2367        cx: &mut ViewContext<Self>,
2368    ) {
2369        match event {
2370            EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2371                let cursor_scroll_position = self.cursor_scroll_position(cx);
2372                if *autoscroll {
2373                    self.scroll_position = cursor_scroll_position;
2374                } else if self.scroll_position != cursor_scroll_position {
2375                    self.scroll_position = None;
2376                }
2377            }
2378            EditorEvent::SelectionsChanged { .. } => {
2379                self.scroll_position = self.cursor_scroll_position(cx);
2380                self.update_active_patch(cx);
2381            }
2382            _ => {}
2383        }
2384        cx.emit(event.clone());
2385    }
2386
2387    fn active_patch(&self) -> Option<(Range<text::Anchor>, &PatchViewState)> {
2388        let patch = self.active_patch.as_ref()?;
2389        Some((patch.clone(), self.patches.get(&patch)?))
2390    }
2391
2392    fn update_active_patch(&mut self, cx: &mut ViewContext<Self>) {
2393        let newest_cursor = self.editor.update(cx, |editor, cx| {
2394            editor.selections.newest::<Point>(cx).head()
2395        });
2396        let context = self.context.read(cx);
2397
2398        let new_patch = context.patch_containing(newest_cursor, cx).cloned();
2399
2400        if new_patch.as_ref().map(|p| &p.range) == self.active_patch.as_ref() {
2401            return;
2402        }
2403
2404        if let Some(old_patch_range) = self.active_patch.take() {
2405            if let Some(patch_state) = self.patches.get_mut(&old_patch_range) {
2406                if let Some(state) = patch_state.editor.take() {
2407                    if let Some(editor) = state.editor.upgrade() {
2408                        self.close_patch_editor(editor, cx);
2409                    }
2410                }
2411            }
2412        }
2413
2414        if let Some(new_patch) = new_patch {
2415            self.active_patch = Some(new_patch.range.clone());
2416
2417            if let Some(patch_state) = self.patches.get_mut(&new_patch.range) {
2418                let mut editor = None;
2419                if let Some(state) = &patch_state.editor {
2420                    if let Some(opened_editor) = state.editor.upgrade() {
2421                        editor = Some(opened_editor);
2422                    }
2423                }
2424
2425                if let Some(editor) = editor {
2426                    self.workspace
2427                        .update(cx, |workspace, cx| {
2428                            workspace.activate_item(&editor, true, false, cx);
2429                        })
2430                        .ok();
2431                } else {
2432                    patch_state.update_task = Some(cx.spawn(move |this, cx| async move {
2433                        Self::open_patch_editor(this, new_patch, cx).await.log_err();
2434                    }));
2435                }
2436            }
2437        }
2438    }
2439
2440    fn close_patch_editor(
2441        &mut self,
2442        editor: View<ProposedChangesEditor>,
2443        cx: &mut ViewContext<ContextEditor>,
2444    ) {
2445        self.workspace
2446            .update(cx, |workspace, cx| {
2447                if let Some(pane) = workspace.pane_for(&editor) {
2448                    pane.update(cx, |pane, cx| {
2449                        let item_id = editor.entity_id();
2450                        if !editor.read(cx).focus_handle(cx).is_focused(cx) {
2451                            pane.close_item_by_id(item_id, SaveIntent::Skip, cx)
2452                                .detach_and_log_err(cx);
2453                        }
2454                    });
2455                }
2456            })
2457            .ok();
2458    }
2459
2460    async fn open_patch_editor(
2461        this: WeakView<Self>,
2462        patch: AssistantPatch,
2463        mut cx: AsyncWindowContext,
2464    ) -> Result<()> {
2465        let project = this.update(&mut cx, |this, _| this.project.clone())?;
2466        let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2467
2468        let editor = cx.new_view(|cx| {
2469            let editor = ProposedChangesEditor::new(
2470                patch.title.clone(),
2471                resolved_patch
2472                    .edit_groups
2473                    .iter()
2474                    .map(|(buffer, groups)| ProposedChangeLocation {
2475                        buffer: buffer.clone(),
2476                        ranges: groups
2477                            .iter()
2478                            .map(|group| group.context_range.clone())
2479                            .collect(),
2480                    })
2481                    .collect(),
2482                Some(project.clone()),
2483                cx,
2484            );
2485            resolved_patch.apply(&editor, cx);
2486            editor
2487        })?;
2488
2489        this.update(&mut cx, |this, cx| {
2490            if let Some(patch_state) = this.patches.get_mut(&patch.range) {
2491                patch_state.editor = Some(PatchEditorState {
2492                    editor: editor.downgrade(),
2493                    opened_patch: patch,
2494                });
2495                patch_state.update_task.take();
2496            }
2497
2498            this.workspace
2499                .update(cx, |workspace, cx| {
2500                    workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
2501                })
2502                .log_err();
2503        })?;
2504
2505        Ok(())
2506    }
2507
2508    async fn update_patch_editor(
2509        this: WeakView<Self>,
2510        patch: AssistantPatch,
2511        mut cx: AsyncWindowContext,
2512    ) -> Result<()> {
2513        let project = this.update(&mut cx, |this, _| this.project.clone())?;
2514        let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2515        this.update(&mut cx, |this, cx| {
2516            let patch_state = this.patches.get_mut(&patch.range)?;
2517
2518            let locations = resolved_patch
2519                .edit_groups
2520                .iter()
2521                .map(|(buffer, groups)| ProposedChangeLocation {
2522                    buffer: buffer.clone(),
2523                    ranges: groups
2524                        .iter()
2525                        .map(|group| group.context_range.clone())
2526                        .collect(),
2527                })
2528                .collect();
2529
2530            if let Some(state) = &mut patch_state.editor {
2531                if let Some(editor) = state.editor.upgrade() {
2532                    editor.update(cx, |editor, cx| {
2533                        editor.set_title(patch.title.clone(), cx);
2534                        editor.reset_locations(locations, cx);
2535                        resolved_patch.apply(editor, cx);
2536                    });
2537
2538                    state.opened_patch = patch;
2539                } else {
2540                    patch_state.editor.take();
2541                }
2542            }
2543            patch_state.update_task.take();
2544
2545            Some(())
2546        })?;
2547        Ok(())
2548    }
2549
2550    fn handle_editor_search_event(
2551        &mut self,
2552        _: View<Editor>,
2553        event: &SearchEvent,
2554        cx: &mut ViewContext<Self>,
2555    ) {
2556        cx.emit(event.clone());
2557    }
2558
2559    fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2560        self.editor.update(cx, |editor, cx| {
2561            let snapshot = editor.snapshot(cx);
2562            let cursor = editor.selections.newest_anchor().head();
2563            let cursor_row = cursor
2564                .to_display_point(&snapshot.display_snapshot)
2565                .row()
2566                .as_f32();
2567            let scroll_position = editor
2568                .scroll_manager
2569                .anchor()
2570                .scroll_position(&snapshot.display_snapshot);
2571
2572            let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2573            if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2574                Some(ScrollPosition {
2575                    cursor,
2576                    offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2577                })
2578            } else {
2579                None
2580            }
2581        })
2582    }
2583
2584    fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2585        self.editor.update(cx, |editor, cx| {
2586            let buffer = editor.buffer().read(cx).snapshot(cx);
2587
2588            let excerpt_id = *buffer.as_singleton().unwrap().0;
2589            let mut old_blocks = std::mem::take(&mut self.blocks);
2590            let mut blocks_to_remove: HashMap<_, _> = old_blocks
2591                .iter()
2592                .map(|(message_id, (_, block_id))| (*message_id, *block_id))
2593                .collect();
2594            let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
2595
2596            let render_block = |message: MessageMetadata| -> RenderBlock {
2597                Box::new({
2598                    let context = self.context.clone();
2599                    move |cx| {
2600                        let message_id = MessageId(message.timestamp);
2601                        let show_spinner = message.role == Role::Assistant
2602                            && message.status == MessageStatus::Pending;
2603
2604                        let label = match message.role {
2605                            Role::User => {
2606                                Label::new("You").color(Color::Default).into_any_element()
2607                            }
2608                            Role::Assistant => {
2609                                let label = Label::new("Assistant").color(Color::Info);
2610                                if show_spinner {
2611                                    label
2612                                        .with_animation(
2613                                            "pulsating-label",
2614                                            Animation::new(Duration::from_secs(2))
2615                                                .repeat()
2616                                                .with_easing(pulsating_between(0.4, 0.8)),
2617                                            |label, delta| label.alpha(delta),
2618                                        )
2619                                        .into_any_element()
2620                                } else {
2621                                    label.into_any_element()
2622                                }
2623                            }
2624
2625                            Role::System => Label::new("System")
2626                                .color(Color::Warning)
2627                                .into_any_element(),
2628                        };
2629
2630                        let sender = ButtonLike::new("role")
2631                            .style(ButtonStyle::Filled)
2632                            .child(label)
2633                            .tooltip(|cx| {
2634                                Tooltip::with_meta(
2635                                    "Toggle message role",
2636                                    None,
2637                                    "Available roles: You (User), Assistant, System",
2638                                    cx,
2639                                )
2640                            })
2641                            .on_click({
2642                                let context = context.clone();
2643                                move |_, cx| {
2644                                    context.update(cx, |context, cx| {
2645                                        context.cycle_message_roles(
2646                                            HashSet::from_iter(Some(message_id)),
2647                                            cx,
2648                                        )
2649                                    })
2650                                }
2651                            });
2652
2653                        h_flex()
2654                            .id(("message_header", message_id.as_u64()))
2655                            .pl(cx.gutter_dimensions.full_width())
2656                            .h_11()
2657                            .w_full()
2658                            .relative()
2659                            .gap_1()
2660                            .child(sender)
2661                            .children(match &message.cache {
2662                                Some(cache) if cache.is_final_anchor => match cache.status {
2663                                    CacheStatus::Cached => Some(
2664                                        div()
2665                                            .id("cached")
2666                                            .child(
2667                                                Icon::new(IconName::DatabaseZap)
2668                                                    .size(IconSize::XSmall)
2669                                                    .color(Color::Hint),
2670                                            )
2671                                            .tooltip(|cx| {
2672                                                Tooltip::with_meta(
2673                                                    "Context cached",
2674                                                    None,
2675                                                    "Large messages cached to optimize performance",
2676                                                    cx,
2677                                                )
2678                                            })
2679                                            .into_any_element(),
2680                                    ),
2681                                    CacheStatus::Pending => Some(
2682                                        div()
2683                                            .child(
2684                                                Icon::new(IconName::Ellipsis)
2685                                                    .size(IconSize::XSmall)
2686                                                    .color(Color::Hint),
2687                                            )
2688                                            .into_any_element(),
2689                                    ),
2690                                },
2691                                _ => None,
2692                            })
2693                            .children(match &message.status {
2694                                MessageStatus::Error(error) => Some(
2695                                    Button::new("show-error", "Error")
2696                                        .color(Color::Error)
2697                                        .selected_label_color(Color::Error)
2698                                        .selected_icon_color(Color::Error)
2699                                        .icon(IconName::XCircle)
2700                                        .icon_color(Color::Error)
2701                                        .icon_size(IconSize::Small)
2702                                        .icon_position(IconPosition::Start)
2703                                        .tooltip(move |cx| {
2704                                            Tooltip::with_meta(
2705                                                "Error interacting with language model",
2706                                                None,
2707                                                "Click for more details",
2708                                                cx,
2709                                            )
2710                                        })
2711                                        .on_click({
2712                                            let context = context.clone();
2713                                            let error = error.clone();
2714                                            move |_, cx| {
2715                                                context.update(cx, |_, cx| {
2716                                                    cx.emit(ContextEvent::ShowAssistError(
2717                                                        error.clone(),
2718                                                    ));
2719                                                });
2720                                            }
2721                                        })
2722                                        .into_any_element(),
2723                                ),
2724                                MessageStatus::Canceled => Some(
2725                                    ButtonLike::new("canceled")
2726                                        .child(Icon::new(IconName::XCircle).color(Color::Disabled))
2727                                        .child(
2728                                            Label::new("Canceled")
2729                                                .size(LabelSize::Small)
2730                                                .color(Color::Disabled),
2731                                        )
2732                                        .tooltip(move |cx| {
2733                                            Tooltip::with_meta(
2734                                                "Canceled",
2735                                                None,
2736                                                "Interaction with the assistant was canceled",
2737                                                cx,
2738                                            )
2739                                        })
2740                                        .into_any_element(),
2741                                ),
2742                                _ => None,
2743                            })
2744                            .into_any_element()
2745                    }
2746                })
2747            };
2748            let create_block_properties = |message: &Message| BlockProperties {
2749                height: 2,
2750                style: BlockStyle::Sticky,
2751                placement: BlockPlacement::Above(
2752                    buffer
2753                        .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
2754                        .unwrap(),
2755                ),
2756                priority: usize::MAX,
2757                render: render_block(MessageMetadata::from(message)),
2758            };
2759            let mut new_blocks = vec![];
2760            let mut block_index_to_message = vec![];
2761            for message in self.context.read(cx).messages(cx) {
2762                if let Some(_) = blocks_to_remove.remove(&message.id) {
2763                    // This is an old message that we might modify.
2764                    let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
2765                        debug_assert!(
2766                            false,
2767                            "old_blocks should contain a message_id we've just removed."
2768                        );
2769                        continue;
2770                    };
2771                    // Should we modify it?
2772                    let message_meta = MessageMetadata::from(&message);
2773                    if meta != &message_meta {
2774                        blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
2775                        *meta = message_meta;
2776                    }
2777                } else {
2778                    // This is a new message.
2779                    new_blocks.push(create_block_properties(&message));
2780                    block_index_to_message.push((message.id, MessageMetadata::from(&message)));
2781                }
2782            }
2783            editor.replace_blocks(blocks_to_replace, None, cx);
2784            editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
2785
2786            let ids = editor.insert_blocks(new_blocks, None, cx);
2787            old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
2788                |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
2789            ));
2790            self.blocks = old_blocks;
2791        });
2792    }
2793
2794    /// Returns either the selected text, or the content of the Markdown code
2795    /// block surrounding the cursor.
2796    fn get_selection_or_code_block(
2797        context_editor_view: &View<ContextEditor>,
2798        cx: &mut ViewContext<Workspace>,
2799    ) -> Option<(String, bool)> {
2800        const CODE_FENCE_DELIMITER: &'static str = "```";
2801
2802        let context_editor = context_editor_view.read(cx).editor.clone();
2803        context_editor.update(cx, |context_editor, cx| {
2804            if context_editor.selections.newest::<Point>(cx).is_empty() {
2805                let snapshot = context_editor.buffer().read(cx).snapshot(cx);
2806                let (_, _, snapshot) = snapshot.as_singleton()?;
2807
2808                let head = context_editor.selections.newest::<Point>(cx).head();
2809                let offset = snapshot.point_to_offset(head);
2810
2811                let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
2812                let mut text = snapshot
2813                    .text_for_range(surrounding_code_block_range)
2814                    .collect::<String>();
2815
2816                // If there is no newline trailing the closing three-backticks, then
2817                // tree-sitter-md extends the range of the content node to include
2818                // the backticks.
2819                if text.ends_with(CODE_FENCE_DELIMITER) {
2820                    text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
2821                }
2822
2823                (!text.is_empty()).then_some((text, true))
2824            } else {
2825                let anchor = context_editor.selections.newest_anchor();
2826                let text = context_editor
2827                    .buffer()
2828                    .read(cx)
2829                    .read(cx)
2830                    .text_for_range(anchor.range())
2831                    .collect::<String>();
2832
2833                (!text.is_empty()).then_some((text, false))
2834            }
2835        })
2836    }
2837
2838    fn insert_selection(
2839        workspace: &mut Workspace,
2840        _: &InsertIntoEditor,
2841        cx: &mut ViewContext<Workspace>,
2842    ) {
2843        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2844            return;
2845        };
2846        let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2847            return;
2848        };
2849        let Some(active_editor_view) = workspace
2850            .active_item(cx)
2851            .and_then(|item| item.act_as::<Editor>(cx))
2852        else {
2853            return;
2854        };
2855
2856        if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
2857            active_editor_view.update(cx, |editor, cx| {
2858                editor.insert(&text, cx);
2859                editor.focus(cx);
2860            })
2861        }
2862    }
2863
2864    fn copy_code(workspace: &mut Workspace, _: &CopyCode, cx: &mut ViewContext<Workspace>) {
2865        let result = maybe!({
2866            let panel = workspace.panel::<AssistantPanel>(cx)?;
2867            let context_editor_view = panel.read(cx).active_context_editor(cx)?;
2868            Self::get_selection_or_code_block(&context_editor_view, cx)
2869        });
2870        let Some((text, is_code_block)) = result else {
2871            return;
2872        };
2873
2874        cx.write_to_clipboard(ClipboardItem::new_string(text));
2875
2876        struct CopyToClipboardToast;
2877        workspace.show_toast(
2878            Toast::new(
2879                NotificationId::unique::<CopyToClipboardToast>(),
2880                format!(
2881                    "{} copied to clipboard.",
2882                    if is_code_block {
2883                        "Code block"
2884                    } else {
2885                        "Selection"
2886                    }
2887                ),
2888            )
2889            .autohide(),
2890            cx,
2891        );
2892    }
2893
2894    fn insert_dragged_files(
2895        workspace: &mut Workspace,
2896        action: &InsertDraggedFiles,
2897        cx: &mut ViewContext<Workspace>,
2898    ) {
2899        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2900            return;
2901        };
2902        let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2903            return;
2904        };
2905
2906        let project = workspace.project().clone();
2907
2908        let paths = match action {
2909            InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
2910            InsertDraggedFiles::ExternalFiles(paths) => {
2911                let tasks = paths
2912                    .clone()
2913                    .into_iter()
2914                    .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
2915                    .collect::<Vec<_>>();
2916
2917                cx.spawn(move |_, cx| async move {
2918                    let mut paths = vec![];
2919                    let mut worktrees = vec![];
2920
2921                    let opened_paths = futures::future::join_all(tasks).await;
2922                    for (worktree, project_path) in opened_paths.into_iter().flatten() {
2923                        let Ok(worktree_root_name) =
2924                            worktree.read_with(&cx, |worktree, _| worktree.root_name().to_string())
2925                        else {
2926                            continue;
2927                        };
2928
2929                        let mut full_path = PathBuf::from(worktree_root_name.clone());
2930                        full_path.push(&project_path.path);
2931                        paths.push(full_path);
2932                        worktrees.push(worktree);
2933                    }
2934
2935                    (paths, worktrees)
2936                })
2937            }
2938        };
2939
2940        cx.spawn(|_, mut cx| async move {
2941            let (paths, dragged_file_worktrees) = paths.await;
2942            let cmd_name = file_command::FileSlashCommand.name();
2943
2944            context_editor_view
2945                .update(&mut cx, |context_editor, cx| {
2946                    let file_argument = paths
2947                        .into_iter()
2948                        .map(|path| path.to_string_lossy().to_string())
2949                        .collect::<Vec<_>>()
2950                        .join(" ");
2951
2952                    context_editor.editor.update(cx, |editor, cx| {
2953                        editor.insert("\n", cx);
2954                        editor.insert(&format!("/{} {}", cmd_name, file_argument), cx);
2955                    });
2956
2957                    context_editor.confirm_command(&ConfirmCommand, cx);
2958
2959                    context_editor
2960                        .dragged_file_worktrees
2961                        .extend(dragged_file_worktrees);
2962                })
2963                .log_err();
2964        })
2965        .detach();
2966    }
2967
2968    fn quote_selection(
2969        workspace: &mut Workspace,
2970        _: &QuoteSelection,
2971        cx: &mut ViewContext<Workspace>,
2972    ) {
2973        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2974            return;
2975        };
2976        let Some(editor) = workspace
2977            .active_item(cx)
2978            .and_then(|item| item.act_as::<Editor>(cx))
2979        else {
2980            return;
2981        };
2982
2983        let mut creases = vec![];
2984        editor.update(cx, |editor, cx| {
2985            let selections = editor.selections.all_adjusted(cx);
2986            let buffer = editor.buffer().read(cx).snapshot(cx);
2987            for selection in selections {
2988                let range = editor::ToOffset::to_offset(&selection.start, &buffer)
2989                    ..editor::ToOffset::to_offset(&selection.end, &buffer);
2990                let selected_text = buffer.text_for_range(range.clone()).collect::<String>();
2991                if selected_text.is_empty() {
2992                    continue;
2993                }
2994                let start_language = buffer.language_at(range.start);
2995                let end_language = buffer.language_at(range.end);
2996                let language_name = if start_language == end_language {
2997                    start_language.map(|language| language.code_fence_block_name())
2998                } else {
2999                    None
3000                };
3001                let language_name = language_name.as_deref().unwrap_or("");
3002                let filename = buffer
3003                    .file_at(selection.start)
3004                    .map(|file| file.full_path(cx));
3005                let text = if language_name == "markdown" {
3006                    selected_text
3007                        .lines()
3008                        .map(|line| format!("> {}", line))
3009                        .collect::<Vec<_>>()
3010                        .join("\n")
3011                } else {
3012                    let start_symbols = buffer
3013                        .symbols_containing(selection.start, None)
3014                        .map(|(_, symbols)| symbols);
3015                    let end_symbols = buffer
3016                        .symbols_containing(selection.end, None)
3017                        .map(|(_, symbols)| symbols);
3018
3019                    let outline_text = if let Some((start_symbols, end_symbols)) =
3020                        start_symbols.zip(end_symbols)
3021                    {
3022                        Some(
3023                            start_symbols
3024                                .into_iter()
3025                                .zip(end_symbols)
3026                                .take_while(|(a, b)| a == b)
3027                                .map(|(a, _)| a.text)
3028                                .collect::<Vec<_>>()
3029                                .join(" > "),
3030                        )
3031                    } else {
3032                        None
3033                    };
3034
3035                    let line_comment_prefix = start_language
3036                        .and_then(|l| l.default_scope().line_comment_prefixes().first().cloned());
3037
3038                    let fence = codeblock_fence_for_path(
3039                        filename.as_deref(),
3040                        Some(selection.start.row..=selection.end.row),
3041                    );
3042
3043                    if let Some((line_comment_prefix, outline_text)) =
3044                        line_comment_prefix.zip(outline_text)
3045                    {
3046                        let breadcrumb =
3047                            format!("{line_comment_prefix}Excerpt from: {outline_text}\n");
3048                        format!("{fence}{breadcrumb}{selected_text}\n```")
3049                    } else {
3050                        format!("{fence}{selected_text}\n```")
3051                    }
3052                };
3053                let crease_title = if let Some(path) = filename {
3054                    let start_line = selection.start.row + 1;
3055                    let end_line = selection.end.row + 1;
3056                    if start_line == end_line {
3057                        format!("{}, Line {}", path.display(), start_line)
3058                    } else {
3059                        format!("{}, Lines {} to {}", path.display(), start_line, end_line)
3060                    }
3061                } else {
3062                    "Quoted selection".to_string()
3063                };
3064                creases.push((text, crease_title));
3065            }
3066        });
3067        if creases.is_empty() {
3068            return;
3069        }
3070        // Activate the panel
3071        if !panel.focus_handle(cx).contains_focused(cx) {
3072            workspace.toggle_panel_focus::<AssistantPanel>(cx);
3073        }
3074
3075        panel.update(cx, |_, cx| {
3076            // Wait to create a new context until the workspace is no longer
3077            // being updated.
3078            cx.defer(move |panel, cx| {
3079                if let Some(context) = panel
3080                    .active_context_editor(cx)
3081                    .or_else(|| panel.new_context(cx))
3082                {
3083                    context.update(cx, |context, cx| {
3084                        context.editor.update(cx, |editor, cx| {
3085                            editor.insert("\n", cx);
3086                            for (text, crease_title) in creases {
3087                                let point = editor.selections.newest::<Point>(cx).head();
3088                                let start_row = MultiBufferRow(point.row);
3089
3090                                editor.insert(&text, cx);
3091
3092                                let snapshot = editor.buffer().read(cx).snapshot(cx);
3093                                let anchor_before = snapshot.anchor_after(point);
3094                                let anchor_after = editor
3095                                    .selections
3096                                    .newest_anchor()
3097                                    .head()
3098                                    .bias_left(&snapshot);
3099
3100                                editor.insert("\n", cx);
3101
3102                                let fold_placeholder = quote_selection_fold_placeholder(
3103                                    crease_title,
3104                                    cx.view().downgrade(),
3105                                );
3106                                let crease = Crease::new(
3107                                    anchor_before..anchor_after,
3108                                    fold_placeholder,
3109                                    render_quote_selection_output_toggle,
3110                                    |_, _, _| Empty.into_any(),
3111                                );
3112                                editor.insert_creases(vec![crease], cx);
3113                                editor.fold_at(
3114                                    &FoldAt {
3115                                        buffer_row: start_row,
3116                                    },
3117                                    cx,
3118                                );
3119                            }
3120                        })
3121                    });
3122                };
3123            });
3124        });
3125    }
3126
3127    fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
3128        if self.editor.read(cx).selections.count() == 1 {
3129            let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
3130            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3131                copied_text,
3132                metadata,
3133            ));
3134            cx.stop_propagation();
3135            return;
3136        }
3137
3138        cx.propagate();
3139    }
3140
3141    fn cut(&mut self, _: &editor::actions::Cut, cx: &mut ViewContext<Self>) {
3142        if self.editor.read(cx).selections.count() == 1 {
3143            let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
3144
3145            self.editor.update(cx, |editor, cx| {
3146                editor.transact(cx, |this, cx| {
3147                    this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3148                        s.select(selections);
3149                    });
3150                    this.insert("", cx);
3151                    cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3152                        copied_text,
3153                        metadata,
3154                    ));
3155                });
3156            });
3157
3158            cx.stop_propagation();
3159            return;
3160        }
3161
3162        cx.propagate();
3163    }
3164
3165    fn get_clipboard_contents(
3166        &mut self,
3167        cx: &mut ViewContext<Self>,
3168    ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
3169        let (snapshot, selection, creases) = self.editor.update(cx, |editor, cx| {
3170            let mut selection = editor.selections.newest::<Point>(cx);
3171            let snapshot = editor.buffer().read(cx).snapshot(cx);
3172
3173            let is_entire_line = selection.is_empty() || editor.selections.line_mode;
3174            if is_entire_line {
3175                selection.start = Point::new(selection.start.row, 0);
3176                selection.end =
3177                    cmp::min(snapshot.max_point(), Point::new(selection.start.row + 1, 0));
3178                selection.goal = SelectionGoal::None;
3179            }
3180
3181            let selection_start = snapshot.point_to_offset(selection.start);
3182
3183            (
3184                snapshot.clone(),
3185                selection.clone(),
3186                editor.display_map.update(cx, |display_map, cx| {
3187                    display_map
3188                        .snapshot(cx)
3189                        .crease_snapshot
3190                        .creases_in_range(
3191                            MultiBufferRow(selection.start.row)
3192                                ..MultiBufferRow(selection.end.row + 1),
3193                            &snapshot,
3194                        )
3195                        .filter_map(|crease| {
3196                            if let Some(metadata) = &crease.metadata {
3197                                let start = crease
3198                                    .range
3199                                    .start
3200                                    .to_offset(&snapshot)
3201                                    .saturating_sub(selection_start);
3202                                let end = crease
3203                                    .range
3204                                    .end
3205                                    .to_offset(&snapshot)
3206                                    .saturating_sub(selection_start);
3207
3208                                let range_relative_to_selection = start..end;
3209
3210                                if range_relative_to_selection.is_empty() {
3211                                    None
3212                                } else {
3213                                    Some(SelectedCreaseMetadata {
3214                                        range_relative_to_selection,
3215                                        crease: metadata.clone(),
3216                                    })
3217                                }
3218                            } else {
3219                                None
3220                            }
3221                        })
3222                        .collect::<Vec<_>>()
3223                }),
3224            )
3225        });
3226
3227        let selection = selection.map(|point| snapshot.point_to_offset(point));
3228        let context = self.context.read(cx);
3229
3230        let mut text = String::new();
3231        for message in context.messages(cx) {
3232            if message.offset_range.start >= selection.range().end {
3233                break;
3234            } else if message.offset_range.end >= selection.range().start {
3235                let range = cmp::max(message.offset_range.start, selection.range().start)
3236                    ..cmp::min(message.offset_range.end, selection.range().end);
3237                if !range.is_empty() {
3238                    for chunk in context.buffer().read(cx).text_for_range(range) {
3239                        text.push_str(chunk);
3240                    }
3241                    if message.offset_range.end < selection.range().end {
3242                        text.push('\n');
3243                    }
3244                }
3245            }
3246        }
3247
3248        (text, CopyMetadata { creases }, vec![selection])
3249    }
3250
3251    fn paste(&mut self, action: &editor::actions::Paste, cx: &mut ViewContext<Self>) {
3252        cx.stop_propagation();
3253
3254        let images = if let Some(item) = cx.read_from_clipboard() {
3255            item.into_entries()
3256                .filter_map(|entry| {
3257                    if let ClipboardEntry::Image(image) = entry {
3258                        Some(image)
3259                    } else {
3260                        None
3261                    }
3262                })
3263                .collect()
3264        } else {
3265            Vec::new()
3266        };
3267
3268        let metadata = if let Some(item) = cx.read_from_clipboard() {
3269            item.entries().first().and_then(|entry| {
3270                if let ClipboardEntry::String(text) = entry {
3271                    text.metadata_json::<CopyMetadata>()
3272                } else {
3273                    None
3274                }
3275            })
3276        } else {
3277            None
3278        };
3279
3280        if images.is_empty() {
3281            self.editor.update(cx, |editor, cx| {
3282                let paste_position = editor.selections.newest::<usize>(cx).head();
3283                editor.paste(action, cx);
3284
3285                if let Some(metadata) = metadata {
3286                    let buffer = editor.buffer().read(cx).snapshot(cx);
3287
3288                    let mut buffer_rows_to_fold = BTreeSet::new();
3289                    let weak_editor = cx.view().downgrade();
3290                    editor.insert_creases(
3291                        metadata.creases.into_iter().map(|metadata| {
3292                            let start = buffer.anchor_after(
3293                                paste_position + metadata.range_relative_to_selection.start,
3294                            );
3295                            let end = buffer.anchor_before(
3296                                paste_position + metadata.range_relative_to_selection.end,
3297                            );
3298
3299                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
3300                            buffer_rows_to_fold.insert(buffer_row);
3301                            Crease::new(
3302                                start..end,
3303                                FoldPlaceholder {
3304                                    constrain_width: false,
3305                                    render: render_fold_icon_button(
3306                                        weak_editor.clone(),
3307                                        metadata.crease.icon,
3308                                        metadata.crease.label.clone(),
3309                                    ),
3310                                    merge_adjacent: false,
3311                                },
3312                                render_slash_command_output_toggle,
3313                                |_, _, _| Empty.into_any(),
3314                            )
3315                            .with_metadata(metadata.crease.clone())
3316                        }),
3317                        cx,
3318                    );
3319                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
3320                        editor.fold_at(&FoldAt { buffer_row }, cx);
3321                    }
3322                }
3323            });
3324        } else {
3325            let mut image_positions = Vec::new();
3326            self.editor.update(cx, |editor, cx| {
3327                editor.transact(cx, |editor, cx| {
3328                    let edits = editor
3329                        .selections
3330                        .all::<usize>(cx)
3331                        .into_iter()
3332                        .map(|selection| (selection.start..selection.end, "\n"));
3333                    editor.edit(edits, cx);
3334
3335                    let snapshot = editor.buffer().read(cx).snapshot(cx);
3336                    for selection in editor.selections.all::<usize>(cx) {
3337                        image_positions.push(snapshot.anchor_before(selection.end));
3338                    }
3339                });
3340            });
3341
3342            self.context.update(cx, |context, cx| {
3343                for image in images {
3344                    let Some(render_image) = image.to_image_data(cx).log_err() else {
3345                        continue;
3346                    };
3347                    let image_id = image.id();
3348                    let image_task = LanguageModelImage::from_image(image, cx).shared();
3349
3350                    for image_position in image_positions.iter() {
3351                        context.insert_content(
3352                            Content::Image {
3353                                anchor: image_position.text_anchor,
3354                                image_id,
3355                                image: image_task.clone(),
3356                                render_image: render_image.clone(),
3357                            },
3358                            cx,
3359                        );
3360                    }
3361                }
3362            });
3363        }
3364    }
3365
3366    fn update_image_blocks(&mut self, cx: &mut ViewContext<Self>) {
3367        self.editor.update(cx, |editor, cx| {
3368            let buffer = editor.buffer().read(cx).snapshot(cx);
3369            let excerpt_id = *buffer.as_singleton().unwrap().0;
3370            let old_blocks = std::mem::take(&mut self.image_blocks);
3371            let new_blocks = self
3372                .context
3373                .read(cx)
3374                .contents(cx)
3375                .filter_map(|content| {
3376                    if let Content::Image {
3377                        anchor,
3378                        render_image,
3379                        ..
3380                    } = content
3381                    {
3382                        Some((anchor, render_image))
3383                    } else {
3384                        None
3385                    }
3386                })
3387                .filter_map(|(anchor, render_image)| {
3388                    const MAX_HEIGHT_IN_LINES: u32 = 8;
3389                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
3390                    let image = render_image.clone();
3391                    anchor.is_valid(&buffer).then(|| BlockProperties {
3392                        placement: BlockPlacement::Above(anchor),
3393                        height: MAX_HEIGHT_IN_LINES,
3394                        style: BlockStyle::Sticky,
3395                        render: Box::new(move |cx| {
3396                            let image_size = size_for_image(
3397                                &image,
3398                                size(
3399                                    cx.max_width - cx.gutter_dimensions.full_width(),
3400                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
3401                                ),
3402                            );
3403                            h_flex()
3404                                .pl(cx.gutter_dimensions.full_width())
3405                                .child(
3406                                    img(image.clone())
3407                                        .object_fit(gpui::ObjectFit::ScaleDown)
3408                                        .w(image_size.width)
3409                                        .h(image_size.height),
3410                                )
3411                                .into_any_element()
3412                        }),
3413                        priority: 0,
3414                    })
3415                })
3416                .collect::<Vec<_>>();
3417
3418            editor.remove_blocks(old_blocks, None, cx);
3419            let ids = editor.insert_blocks(new_blocks, None, cx);
3420            self.image_blocks = HashSet::from_iter(ids);
3421        });
3422    }
3423
3424    fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
3425        self.context.update(cx, |context, cx| {
3426            let selections = self.editor.read(cx).selections.disjoint_anchors();
3427            for selection in selections.as_ref() {
3428                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
3429                let range = selection
3430                    .map(|endpoint| endpoint.to_offset(&buffer))
3431                    .range();
3432                context.split_message(range, cx);
3433            }
3434        });
3435    }
3436
3437    fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
3438        self.context.update(cx, |context, cx| {
3439            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
3440        });
3441    }
3442
3443    fn title(&self, cx: &AppContext) -> Cow<str> {
3444        self.context
3445            .read(cx)
3446            .summary()
3447            .map(|summary| summary.text.clone())
3448            .map(Cow::Owned)
3449            .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
3450    }
3451
3452    fn render_patch_header(
3453        &self,
3454        range: Range<text::Anchor>,
3455        _id: FoldId,
3456        cx: &mut ViewContext<Self>,
3457    ) -> Option<AnyElement> {
3458        let patch = self.context.read(cx).patch_for_range(&range, cx)?;
3459        let theme = cx.theme().clone();
3460        Some(
3461            h_flex()
3462                .px_1()
3463                .py_0p5()
3464                .border_b_1()
3465                .border_color(theme.status().info_border)
3466                .gap_1()
3467                .child(Icon::new(IconName::Diff).size(IconSize::Small))
3468                .child(Label::new(patch.title.clone()).size(LabelSize::Small))
3469                .into_any(),
3470        )
3471    }
3472
3473    fn render_patch_footer(
3474        &mut self,
3475        range: Range<text::Anchor>,
3476        max_width: Pixels,
3477        gutter_width: Pixels,
3478        id: BlockId,
3479        cx: &mut ViewContext<Self>,
3480    ) -> Option<AnyElement> {
3481        let snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3482        let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
3483        let excerpt_id = *excerpt_id;
3484        let anchor = snapshot
3485            .buffer_snapshot
3486            .anchor_in_excerpt(excerpt_id, range.start)
3487            .unwrap();
3488
3489        if !snapshot.intersects_fold(anchor) {
3490            return None;
3491        }
3492
3493        let patch = self.context.read(cx).patch_for_range(&range, cx)?;
3494        let paths = patch
3495            .paths()
3496            .map(|p| SharedString::from(p.to_string()))
3497            .collect::<BTreeSet<_>>();
3498
3499        Some(
3500            v_flex()
3501                .id(id)
3502                .pl(gutter_width)
3503                .w(max_width)
3504                .py_2()
3505                .cursor(CursorStyle::PointingHand)
3506                .on_click(cx.listener(move |this, _, cx| {
3507                    this.editor.update(cx, |editor, cx| {
3508                        editor.change_selections(None, cx, |selections| {
3509                            selections.select_ranges(vec![anchor..anchor]);
3510                        });
3511                    });
3512                    this.focus_active_patch(cx);
3513                }))
3514                .children(paths.into_iter().map(|path| {
3515                    h_flex()
3516                        .pl_1()
3517                        .gap_1()
3518                        .child(Icon::new(IconName::File).size(IconSize::Small))
3519                        .child(Label::new(path).size(LabelSize::Small))
3520                }))
3521                .when(patch.status == AssistantPatchStatus::Pending, |div| {
3522                    div.child(
3523                        Label::new("Generating")
3524                            .color(Color::Muted)
3525                            .size(LabelSize::Small)
3526                            .with_animation(
3527                                "pulsating-label",
3528                                Animation::new(Duration::from_secs(2))
3529                                    .repeat()
3530                                    .with_easing(pulsating_between(0.4, 1.)),
3531                                |label, delta| label.alpha(delta),
3532                            ),
3533                    )
3534                })
3535                .into_any(),
3536        )
3537    }
3538
3539    fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3540        use feature_flags::FeatureFlagAppExt;
3541        let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
3542            assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
3543        });
3544
3545        if nudge.map_or(false, |value| value) {
3546            Some(
3547                h_flex()
3548                    .p_3()
3549                    .border_b_1()
3550                    .border_color(cx.theme().colors().border_variant)
3551                    .bg(cx.theme().colors().editor_background)
3552                    .justify_between()
3553                    .child(
3554                        h_flex()
3555                            .gap_3()
3556                            .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
3557                            .child(Label::new("Zed AI is here! Get started by signing in →")),
3558                    )
3559                    .child(
3560                        Button::new("sign-in", "Sign in")
3561                            .size(ButtonSize::Compact)
3562                            .style(ButtonStyle::Filled)
3563                            .on_click(cx.listener(|this, _event, cx| {
3564                                let client = this
3565                                    .workspace
3566                                    .update(cx, |workspace, _| workspace.client().clone())
3567                                    .log_err();
3568
3569                                if let Some(client) = client {
3570                                    cx.spawn(|this, mut cx| async move {
3571                                        client.authenticate_and_connect(true, &mut cx).await?;
3572                                        this.update(&mut cx, |_, cx| cx.notify())
3573                                    })
3574                                    .detach_and_log_err(cx)
3575                                }
3576                            })),
3577                    )
3578                    .into_any_element(),
3579            )
3580        } else if let Some(configuration_error) = configuration_error(cx) {
3581            let label = match configuration_error {
3582                ConfigurationError::NoProvider => "No LLM provider selected.",
3583                ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
3584            };
3585            Some(
3586                h_flex()
3587                    .px_3()
3588                    .py_2()
3589                    .border_b_1()
3590                    .border_color(cx.theme().colors().border_variant)
3591                    .bg(cx.theme().colors().editor_background)
3592                    .justify_between()
3593                    .child(
3594                        h_flex()
3595                            .gap_3()
3596                            .child(
3597                                Icon::new(IconName::Warning)
3598                                    .size(IconSize::Small)
3599                                    .color(Color::Warning),
3600                            )
3601                            .child(Label::new(label)),
3602                    )
3603                    .child(
3604                        Button::new("open-configuration", "Configure Providers")
3605                            .size(ButtonSize::Compact)
3606                            .icon(Some(IconName::SlidersVertical))
3607                            .icon_size(IconSize::Small)
3608                            .icon_position(IconPosition::Start)
3609                            .style(ButtonStyle::Filled)
3610                            .on_click({
3611                                let focus_handle = self.focus_handle(cx).clone();
3612                                move |_event, cx| {
3613                                    focus_handle.dispatch_action(&ShowConfiguration, cx);
3614                                }
3615                            }),
3616                    )
3617                    .into_any_element(),
3618            )
3619        } else {
3620            None
3621        }
3622    }
3623
3624    fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3625        let focus_handle = self.focus_handle(cx).clone();
3626
3627        let (style, tooltip) = match token_state(&self.context, cx) {
3628            Some(TokenState::NoTokensLeft { .. }) => (
3629                ButtonStyle::Tinted(TintColor::Negative),
3630                Some(Tooltip::text("Token limit reached", cx)),
3631            ),
3632            Some(TokenState::HasMoreTokens {
3633                over_warn_threshold,
3634                ..
3635            }) => {
3636                let (style, tooltip) = if over_warn_threshold {
3637                    (
3638                        ButtonStyle::Tinted(TintColor::Warning),
3639                        Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3640                    )
3641                } else {
3642                    (ButtonStyle::Filled, None)
3643                };
3644                (style, tooltip)
3645            }
3646            None => (ButtonStyle::Filled, None),
3647        };
3648
3649        let provider = LanguageModelRegistry::read_global(cx).active_provider();
3650
3651        let has_configuration_error = configuration_error(cx).is_some();
3652        let needs_to_accept_terms = self.show_accept_terms
3653            && provider
3654                .as_ref()
3655                .map_or(false, |provider| provider.must_accept_terms(cx));
3656        let disabled = has_configuration_error || needs_to_accept_terms;
3657
3658        ButtonLike::new("send_button")
3659            .disabled(disabled)
3660            .style(style)
3661            .when_some(tooltip, |button, tooltip| {
3662                button.tooltip(move |_| tooltip.clone())
3663            })
3664            .layer(ElevationIndex::ModalSurface)
3665            .child(Label::new(
3666                if AssistantSettings::get_global(cx).are_live_diffs_enabled(cx) {
3667                    "Chat"
3668                } else {
3669                    "Send"
3670                },
3671            ))
3672            .children(
3673                KeyBinding::for_action_in(&Assist, &focus_handle, cx)
3674                    .map(|binding| binding.into_any_element()),
3675            )
3676            .on_click(move |_event, cx| {
3677                focus_handle.dispatch_action(&Assist, cx);
3678            })
3679    }
3680
3681    fn render_edit_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3682        let focus_handle = self.focus_handle(cx).clone();
3683
3684        let (style, tooltip) = match token_state(&self.context, cx) {
3685            Some(TokenState::NoTokensLeft { .. }) => (
3686                ButtonStyle::Tinted(TintColor::Negative),
3687                Some(Tooltip::text("Token limit reached", cx)),
3688            ),
3689            Some(TokenState::HasMoreTokens {
3690                over_warn_threshold,
3691                ..
3692            }) => {
3693                let (style, tooltip) = if over_warn_threshold {
3694                    (
3695                        ButtonStyle::Tinted(TintColor::Warning),
3696                        Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3697                    )
3698                } else {
3699                    (ButtonStyle::Filled, None)
3700                };
3701                (style, tooltip)
3702            }
3703            None => (ButtonStyle::Filled, None),
3704        };
3705
3706        let provider = LanguageModelRegistry::read_global(cx).active_provider();
3707
3708        let has_configuration_error = configuration_error(cx).is_some();
3709        let needs_to_accept_terms = self.show_accept_terms
3710            && provider
3711                .as_ref()
3712                .map_or(false, |provider| provider.must_accept_terms(cx));
3713        let disabled = has_configuration_error || needs_to_accept_terms;
3714
3715        ButtonLike::new("edit_button")
3716            .disabled(disabled)
3717            .style(style)
3718            .when_some(tooltip, |button, tooltip| {
3719                button.tooltip(move |_| tooltip.clone())
3720            })
3721            .layer(ElevationIndex::ModalSurface)
3722            .child(Label::new("Suggest Edits"))
3723            .children(
3724                KeyBinding::for_action_in(&Edit, &focus_handle, cx)
3725                    .map(|binding| binding.into_any_element()),
3726            )
3727            .on_click(move |_event, cx| {
3728                focus_handle.dispatch_action(&Edit, cx);
3729            })
3730    }
3731
3732    fn render_last_error(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3733        let last_error = self.last_error.as_ref()?;
3734
3735        Some(
3736            div()
3737                .absolute()
3738                .right_3()
3739                .bottom_12()
3740                .max_w_96()
3741                .py_2()
3742                .px_3()
3743                .elevation_2(cx)
3744                .occlude()
3745                .child(match last_error {
3746                    AssistError::FileRequired => self.render_file_required_error(cx),
3747                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
3748                    AssistError::MaxMonthlySpendReached => {
3749                        self.render_max_monthly_spend_reached_error(cx)
3750                    }
3751                    AssistError::Message(error_message) => {
3752                        self.render_assist_error(error_message, cx)
3753                    }
3754                })
3755                .into_any(),
3756        )
3757    }
3758
3759    fn render_file_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3760        v_flex()
3761            .gap_0p5()
3762            .child(
3763                h_flex()
3764                    .gap_1p5()
3765                    .items_center()
3766                    .child(Icon::new(IconName::Warning).color(Color::Warning))
3767                    .child(
3768                        Label::new("Suggest Edits needs a file to edit").weight(FontWeight::MEDIUM),
3769                    ),
3770            )
3771            .child(
3772                div()
3773                    .id("error-message")
3774                    .max_h_24()
3775                    .overflow_y_scroll()
3776                    .child(Label::new(
3777                        "To include files, type /file or /tab in your prompt.",
3778                    )),
3779            )
3780            .child(
3781                h_flex()
3782                    .justify_end()
3783                    .mt_1()
3784                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3785                        |this, _, cx| {
3786                            this.last_error = None;
3787                            cx.notify();
3788                        },
3789                    ))),
3790            )
3791            .into_any()
3792    }
3793
3794    fn render_payment_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3795        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.";
3796
3797        v_flex()
3798            .gap_0p5()
3799            .child(
3800                h_flex()
3801                    .gap_1p5()
3802                    .items_center()
3803                    .child(Icon::new(IconName::XCircle).color(Color::Error))
3804                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
3805            )
3806            .child(
3807                div()
3808                    .id("error-message")
3809                    .max_h_24()
3810                    .overflow_y_scroll()
3811                    .child(Label::new(ERROR_MESSAGE)),
3812            )
3813            .child(
3814                h_flex()
3815                    .justify_end()
3816                    .mt_1()
3817                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
3818                        |this, _, cx| {
3819                            this.last_error = None;
3820                            cx.open_url(&zed_urls::account_url(cx));
3821                            cx.notify();
3822                        },
3823                    )))
3824                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3825                        |this, _, cx| {
3826                            this.last_error = None;
3827                            cx.notify();
3828                        },
3829                    ))),
3830            )
3831            .into_any()
3832    }
3833
3834    fn render_max_monthly_spend_reached_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3835        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
3836
3837        v_flex()
3838            .gap_0p5()
3839            .child(
3840                h_flex()
3841                    .gap_1p5()
3842                    .items_center()
3843                    .child(Icon::new(IconName::XCircle).color(Color::Error))
3844                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
3845            )
3846            .child(
3847                div()
3848                    .id("error-message")
3849                    .max_h_24()
3850                    .overflow_y_scroll()
3851                    .child(Label::new(ERROR_MESSAGE)),
3852            )
3853            .child(
3854                h_flex()
3855                    .justify_end()
3856                    .mt_1()
3857                    .child(
3858                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
3859                            cx.listener(|this, _, cx| {
3860                                this.last_error = None;
3861                                cx.open_url(&zed_urls::account_url(cx));
3862                                cx.notify();
3863                            }),
3864                        ),
3865                    )
3866                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3867                        |this, _, cx| {
3868                            this.last_error = None;
3869                            cx.notify();
3870                        },
3871                    ))),
3872            )
3873            .into_any()
3874    }
3875
3876    fn render_assist_error(
3877        &self,
3878        error_message: &SharedString,
3879        cx: &mut ViewContext<Self>,
3880    ) -> AnyElement {
3881        v_flex()
3882            .gap_0p5()
3883            .child(
3884                h_flex()
3885                    .gap_1p5()
3886                    .items_center()
3887                    .child(Icon::new(IconName::XCircle).color(Color::Error))
3888                    .child(
3889                        Label::new("Error interacting with language model")
3890                            .weight(FontWeight::MEDIUM),
3891                    ),
3892            )
3893            .child(
3894                div()
3895                    .id("error-message")
3896                    .max_h_24()
3897                    .overflow_y_scroll()
3898                    .child(Label::new(error_message.clone())),
3899            )
3900            .child(
3901                h_flex()
3902                    .justify_end()
3903                    .mt_1()
3904                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3905                        |this, _, cx| {
3906                            this.last_error = None;
3907                            cx.notify();
3908                        },
3909                    ))),
3910            )
3911            .into_any()
3912    }
3913}
3914
3915/// Returns the contents of the *outermost* fenced code block that contains the given offset.
3916fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
3917    const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
3918    const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
3919
3920    let layer = snapshot.syntax_layers().next()?;
3921
3922    let root_node = layer.node();
3923    let mut cursor = root_node.walk();
3924
3925    // Go to the first child for the given offset
3926    while cursor.goto_first_child_for_byte(offset).is_some() {
3927        // If we're at the end of the node, go to the next one.
3928        // Example: if you have a fenced-code-block, and you're on the start of the line
3929        // right after the closing ```, you want to skip the fenced-code-block and
3930        // go to the next sibling.
3931        if cursor.node().end_byte() == offset {
3932            cursor.goto_next_sibling();
3933        }
3934
3935        if cursor.node().start_byte() > offset {
3936            break;
3937        }
3938
3939        // We found the fenced code block.
3940        if cursor.node().kind() == CODE_BLOCK_NODE {
3941            // Now we need to find the child node that contains the code.
3942            cursor.goto_first_child();
3943            loop {
3944                if cursor.node().kind() == CODE_BLOCK_CONTENT {
3945                    return Some(cursor.node().byte_range());
3946                }
3947                if !cursor.goto_next_sibling() {
3948                    break;
3949                }
3950            }
3951        }
3952    }
3953
3954    None
3955}
3956
3957fn render_fold_icon_button(
3958    editor: WeakView<Editor>,
3959    icon: IconName,
3960    label: SharedString,
3961) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut WindowContext) -> AnyElement> {
3962    Arc::new(move |fold_id, fold_range, _cx| {
3963        let editor = editor.clone();
3964        ButtonLike::new(fold_id)
3965            .style(ButtonStyle::Filled)
3966            .layer(ElevationIndex::ElevatedSurface)
3967            .child(Icon::new(icon))
3968            .child(Label::new(label.clone()).single_line())
3969            .on_click(move |_, cx| {
3970                editor
3971                    .update(cx, |editor, cx| {
3972                        let buffer_start = fold_range
3973                            .start
3974                            .to_point(&editor.buffer().read(cx).read(cx));
3975                        let buffer_row = MultiBufferRow(buffer_start.row);
3976                        editor.unfold_at(&UnfoldAt { buffer_row }, cx);
3977                    })
3978                    .ok();
3979            })
3980            .into_any_element()
3981    })
3982}
3983
3984#[derive(Debug, Clone, Serialize, Deserialize)]
3985struct CopyMetadata {
3986    creases: Vec<SelectedCreaseMetadata>,
3987}
3988
3989#[derive(Debug, Clone, Serialize, Deserialize)]
3990struct SelectedCreaseMetadata {
3991    range_relative_to_selection: Range<usize>,
3992    crease: CreaseMetadata,
3993}
3994
3995impl EventEmitter<EditorEvent> for ContextEditor {}
3996impl EventEmitter<SearchEvent> for ContextEditor {}
3997
3998impl Render for ContextEditor {
3999    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4000        let provider = LanguageModelRegistry::read_global(cx).active_provider();
4001        let accept_terms = if self.show_accept_terms {
4002            provider
4003                .as_ref()
4004                .and_then(|provider| provider.render_accept_terms(cx))
4005        } else {
4006            None
4007        };
4008
4009        v_flex()
4010            .key_context("ContextEditor")
4011            .capture_action(cx.listener(ContextEditor::cancel))
4012            .capture_action(cx.listener(ContextEditor::save))
4013            .capture_action(cx.listener(ContextEditor::copy))
4014            .capture_action(cx.listener(ContextEditor::cut))
4015            .capture_action(cx.listener(ContextEditor::paste))
4016            .capture_action(cx.listener(ContextEditor::cycle_message_role))
4017            .capture_action(cx.listener(ContextEditor::confirm_command))
4018            .on_action(cx.listener(ContextEditor::edit))
4019            .on_action(cx.listener(ContextEditor::assist))
4020            .on_action(cx.listener(ContextEditor::split))
4021            .size_full()
4022            .children(self.render_notice(cx))
4023            .child(
4024                div()
4025                    .flex_grow()
4026                    .bg(cx.theme().colors().editor_background)
4027                    .child(self.editor.clone()),
4028            )
4029            .when_some(accept_terms, |this, element| {
4030                this.child(
4031                    div()
4032                        .absolute()
4033                        .right_3()
4034                        .bottom_12()
4035                        .max_w_96()
4036                        .py_2()
4037                        .px_3()
4038                        .elevation_2(cx)
4039                        .bg(cx.theme().colors().surface_background)
4040                        .occlude()
4041                        .child(element),
4042                )
4043            })
4044            .children(self.render_last_error(cx))
4045            .child(
4046                h_flex().w_full().relative().child(
4047                    h_flex()
4048                        .p_2()
4049                        .w_full()
4050                        .border_t_1()
4051                        .border_color(cx.theme().colors().border_variant)
4052                        .bg(cx.theme().colors().editor_background)
4053                        .child(
4054                            h_flex()
4055                                .gap_1()
4056                                .child(render_inject_context_menu(cx.view().downgrade(), cx)),
4057                        )
4058                        .child(
4059                            h_flex()
4060                                .w_full()
4061                                .justify_end()
4062                                .when(
4063                                    AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
4064                                    |buttons| {
4065                                        buttons
4066                                            .items_center()
4067                                            .gap_1p5()
4068                                            .child(self.render_edit_button(cx))
4069                                            .child(
4070                                                Label::new("or")
4071                                                    .size(LabelSize::Small)
4072                                                    .color(Color::Muted),
4073                                            )
4074                                    },
4075                                )
4076                                .child(self.render_send_button(cx)),
4077                        ),
4078                ),
4079            )
4080    }
4081}
4082
4083impl FocusableView for ContextEditor {
4084    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4085        self.editor.focus_handle(cx)
4086    }
4087}
4088
4089impl Item for ContextEditor {
4090    type Event = editor::EditorEvent;
4091
4092    fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
4093        Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
4094    }
4095
4096    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
4097        match event {
4098            EditorEvent::Edited { .. } => {
4099                f(item::ItemEvent::Edit);
4100            }
4101            EditorEvent::TitleChanged => {
4102                f(item::ItemEvent::UpdateTab);
4103            }
4104            _ => {}
4105        }
4106    }
4107
4108    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
4109        Some(self.title(cx).to_string().into())
4110    }
4111
4112    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
4113        Some(Box::new(handle.clone()))
4114    }
4115
4116    fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
4117        self.editor.update(cx, |editor, cx| {
4118            Item::set_nav_history(editor, nav_history, cx)
4119        })
4120    }
4121
4122    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
4123        self.editor
4124            .update(cx, |editor, cx| Item::navigate(editor, data, cx))
4125    }
4126
4127    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
4128        self.editor.update(cx, Item::deactivated)
4129    }
4130}
4131
4132impl SearchableItem for ContextEditor {
4133    type Match = <Editor as SearchableItem>::Match;
4134
4135    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
4136        self.editor.update(cx, |editor, cx| {
4137            editor.clear_matches(cx);
4138        });
4139    }
4140
4141    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4142        self.editor
4143            .update(cx, |editor, cx| editor.update_matches(matches, cx));
4144    }
4145
4146    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
4147        self.editor
4148            .update(cx, |editor, cx| editor.query_suggestion(cx))
4149    }
4150
4151    fn activate_match(
4152        &mut self,
4153        index: usize,
4154        matches: &[Self::Match],
4155        cx: &mut ViewContext<Self>,
4156    ) {
4157        self.editor.update(cx, |editor, cx| {
4158            editor.activate_match(index, matches, cx);
4159        });
4160    }
4161
4162    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4163        self.editor
4164            .update(cx, |editor, cx| editor.select_matches(matches, cx));
4165    }
4166
4167    fn replace(
4168        &mut self,
4169        identifier: &Self::Match,
4170        query: &project::search::SearchQuery,
4171        cx: &mut ViewContext<Self>,
4172    ) {
4173        self.editor
4174            .update(cx, |editor, cx| editor.replace(identifier, query, cx));
4175    }
4176
4177    fn find_matches(
4178        &mut self,
4179        query: Arc<project::search::SearchQuery>,
4180        cx: &mut ViewContext<Self>,
4181    ) -> Task<Vec<Self::Match>> {
4182        self.editor
4183            .update(cx, |editor, cx| editor.find_matches(query, cx))
4184    }
4185
4186    fn active_match_index(
4187        &mut self,
4188        matches: &[Self::Match],
4189        cx: &mut ViewContext<Self>,
4190    ) -> Option<usize> {
4191        self.editor
4192            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
4193    }
4194}
4195
4196impl FollowableItem for ContextEditor {
4197    fn remote_id(&self) -> Option<workspace::ViewId> {
4198        self.remote_id
4199    }
4200
4201    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
4202        let context = self.context.read(cx);
4203        Some(proto::view::Variant::ContextEditor(
4204            proto::view::ContextEditor {
4205                context_id: context.id().to_proto(),
4206                editor: if let Some(proto::view::Variant::Editor(proto)) =
4207                    self.editor.read(cx).to_state_proto(cx)
4208                {
4209                    Some(proto)
4210                } else {
4211                    None
4212                },
4213            },
4214        ))
4215    }
4216
4217    fn from_state_proto(
4218        workspace: View<Workspace>,
4219        id: workspace::ViewId,
4220        state: &mut Option<proto::view::Variant>,
4221        cx: &mut WindowContext,
4222    ) -> Option<Task<Result<View<Self>>>> {
4223        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
4224            return None;
4225        };
4226        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
4227            unreachable!()
4228        };
4229
4230        let context_id = ContextId::from_proto(state.context_id);
4231        let editor_state = state.editor?;
4232
4233        let (project, panel) = workspace.update(cx, |workspace, cx| {
4234            Some((
4235                workspace.project().clone(),
4236                workspace.panel::<AssistantPanel>(cx)?,
4237            ))
4238        })?;
4239
4240        let context_editor =
4241            panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
4242
4243        Some(cx.spawn(|mut cx| async move {
4244            let context_editor = context_editor.await?;
4245            context_editor
4246                .update(&mut cx, |context_editor, cx| {
4247                    context_editor.remote_id = Some(id);
4248                    context_editor.editor.update(cx, |editor, cx| {
4249                        editor.apply_update_proto(
4250                            &project,
4251                            proto::update_view::Variant::Editor(proto::update_view::Editor {
4252                                selections: editor_state.selections,
4253                                pending_selection: editor_state.pending_selection,
4254                                scroll_top_anchor: editor_state.scroll_top_anchor,
4255                                scroll_x: editor_state.scroll_y,
4256                                scroll_y: editor_state.scroll_y,
4257                                ..Default::default()
4258                            }),
4259                            cx,
4260                        )
4261                    })
4262                })?
4263                .await?;
4264            Ok(context_editor)
4265        }))
4266    }
4267
4268    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
4269        Editor::to_follow_event(event)
4270    }
4271
4272    fn add_event_to_update_proto(
4273        &self,
4274        event: &Self::Event,
4275        update: &mut Option<proto::update_view::Variant>,
4276        cx: &WindowContext,
4277    ) -> bool {
4278        self.editor
4279            .read(cx)
4280            .add_event_to_update_proto(event, update, cx)
4281    }
4282
4283    fn apply_update_proto(
4284        &mut self,
4285        project: &Model<Project>,
4286        message: proto::update_view::Variant,
4287        cx: &mut ViewContext<Self>,
4288    ) -> Task<Result<()>> {
4289        self.editor.update(cx, |editor, cx| {
4290            editor.apply_update_proto(project, message, cx)
4291        })
4292    }
4293
4294    fn is_project_item(&self, _cx: &WindowContext) -> bool {
4295        true
4296    }
4297
4298    fn set_leader_peer_id(
4299        &mut self,
4300        leader_peer_id: Option<proto::PeerId>,
4301        cx: &mut ViewContext<Self>,
4302    ) {
4303        self.editor.update(cx, |editor, cx| {
4304            editor.set_leader_peer_id(leader_peer_id, cx)
4305        })
4306    }
4307
4308    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
4309        if existing.context.read(cx).id() == self.context.read(cx).id() {
4310            Some(item::Dedup::KeepExisting)
4311        } else {
4312            None
4313        }
4314    }
4315}
4316
4317pub struct ContextEditorToolbarItem {
4318    fs: Arc<dyn Fs>,
4319    workspace: WeakView<Workspace>,
4320    active_context_editor: Option<WeakView<ContextEditor>>,
4321    model_summary_editor: View<Editor>,
4322    model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4323}
4324
4325fn active_editor_focus_handle(
4326    workspace: &WeakView<Workspace>,
4327    cx: &WindowContext<'_>,
4328) -> Option<FocusHandle> {
4329    workspace.upgrade().and_then(|workspace| {
4330        Some(
4331            workspace
4332                .read(cx)
4333                .active_item_as::<Editor>(cx)?
4334                .focus_handle(cx),
4335        )
4336    })
4337}
4338
4339fn render_inject_context_menu(
4340    active_context_editor: WeakView<ContextEditor>,
4341    cx: &mut WindowContext<'_>,
4342) -> impl IntoElement {
4343    let commands = SlashCommandRegistry::global(cx);
4344
4345    slash_command_picker::SlashCommandSelector::new(
4346        commands.clone(),
4347        active_context_editor,
4348        Button::new("trigger", "Add Context")
4349            .icon(IconName::Plus)
4350            .icon_size(IconSize::Small)
4351            .icon_color(Color::Muted)
4352            .icon_position(IconPosition::Start)
4353            .tooltip(|cx| Tooltip::text("Type / to insert via keyboard", cx)),
4354    )
4355}
4356
4357impl ContextEditorToolbarItem {
4358    pub fn new(
4359        workspace: &Workspace,
4360        model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4361        model_summary_editor: View<Editor>,
4362    ) -> Self {
4363        Self {
4364            fs: workspace.app_state().fs.clone(),
4365            workspace: workspace.weak_handle(),
4366            active_context_editor: None,
4367            model_summary_editor,
4368            model_selector_menu_handle,
4369        }
4370    }
4371
4372    fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
4373        let context = &self
4374            .active_context_editor
4375            .as_ref()?
4376            .upgrade()?
4377            .read(cx)
4378            .context;
4379        let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
4380            TokenState::NoTokensLeft {
4381                max_token_count,
4382                token_count,
4383            } => (Color::Error, token_count, max_token_count),
4384            TokenState::HasMoreTokens {
4385                max_token_count,
4386                token_count,
4387                over_warn_threshold,
4388            } => {
4389                let color = if over_warn_threshold {
4390                    Color::Warning
4391                } else {
4392                    Color::Muted
4393                };
4394                (color, token_count, max_token_count)
4395            }
4396        };
4397        Some(
4398            h_flex()
4399                .gap_0p5()
4400                .child(
4401                    Label::new(humanize_token_count(token_count))
4402                        .size(LabelSize::Small)
4403                        .color(token_count_color),
4404                )
4405                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
4406                .child(
4407                    Label::new(humanize_token_count(max_token_count))
4408                        .size(LabelSize::Small)
4409                        .color(Color::Muted),
4410                ),
4411        )
4412    }
4413}
4414
4415impl Render for ContextEditorToolbarItem {
4416    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4417        let left_side = h_flex()
4418            .pl_1()
4419            .gap_2()
4420            .flex_1()
4421            .min_w(rems(DEFAULT_TAB_TITLE.len() as f32))
4422            .when(self.active_context_editor.is_some(), |left_side| {
4423                left_side.child(self.model_summary_editor.clone())
4424            });
4425        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
4426        let active_model = LanguageModelRegistry::read_global(cx).active_model();
4427        let weak_self = cx.view().downgrade();
4428        let right_side = h_flex()
4429            .gap_2()
4430            // TODO display this in a nicer way, once we have a design for it.
4431            // .children({
4432            //     let project = self
4433            //         .workspace
4434            //         .upgrade()
4435            //         .map(|workspace| workspace.read(cx).project().downgrade());
4436            //
4437            //     let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
4438            //         project.and_then(|project| db.remaining_summaries(&project, cx))
4439            //     });
4440
4441            //     scan_items_remaining
4442            //         .map(|remaining_items| format!("Files to scan: {}", remaining_items))
4443            // })
4444            .child(
4445                ModelSelector::new(
4446                    self.fs.clone(),
4447                    ButtonLike::new("active-model")
4448                        .style(ButtonStyle::Subtle)
4449                        .child(
4450                            h_flex()
4451                                .w_full()
4452                                .gap_0p5()
4453                                .child(
4454                                    div()
4455                                        .overflow_x_hidden()
4456                                        .flex_grow()
4457                                        .whitespace_nowrap()
4458                                        .child(match (active_provider, active_model) {
4459                                            (Some(provider), Some(model)) => h_flex()
4460                                                .gap_1()
4461                                                .child(
4462                                                    Icon::new(model.icon().unwrap_or_else(|| provider.icon()))
4463                                                        .color(Color::Muted)
4464                                                        .size(IconSize::XSmall),
4465                                                )
4466                                                .child(
4467                                                    Label::new(model.name().0)
4468                                                        .size(LabelSize::Small)
4469                                                        .color(Color::Muted),
4470                                                )
4471                                                .into_any_element(),
4472                                            _ => Label::new("No model selected")
4473                                                .size(LabelSize::Small)
4474                                                .color(Color::Muted)
4475                                                .into_any_element(),
4476                                        }),
4477                                )
4478                                .child(
4479                                    Icon::new(IconName::ChevronDown)
4480                                        .color(Color::Muted)
4481                                        .size(IconSize::XSmall),
4482                                ),
4483                        )
4484                        .tooltip(move |cx| {
4485                            Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
4486                        }),
4487                )
4488                .with_handle(self.model_selector_menu_handle.clone()),
4489            )
4490            .children(self.render_remaining_tokens(cx))
4491            .child(
4492                PopoverMenu::new("context-editor-popover")
4493                    .trigger(
4494                        IconButton::new("context-editor-trigger", IconName::EllipsisVertical)
4495                            .icon_size(IconSize::Small)
4496                            .tooltip(|cx| Tooltip::text("Open Context Options", cx)),
4497                    )
4498                    .menu({
4499                        let weak_self = weak_self.clone();
4500                        move |cx| {
4501                            let weak_self = weak_self.clone();
4502                            Some(ContextMenu::build(cx, move |menu, cx| {
4503                                let context = weak_self
4504                                    .update(cx, |this, cx| {
4505                                        active_editor_focus_handle(&this.workspace, cx)
4506                                    })
4507                                    .ok()
4508                                    .flatten();
4509                                menu.when_some(context, |menu, context| menu.context(context))
4510                                    .entry("Regenerate Context Title", None, {
4511                                        let weak_self = weak_self.clone();
4512                                        move |cx| {
4513                                            weak_self
4514                                                .update(cx, |_, cx| {
4515                                                    cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
4516                                                })
4517                                                .ok();
4518                                        }
4519                                    })
4520                                    .custom_entry(
4521                                        |_| {
4522                                            h_flex()
4523                                                .w_full()
4524                                                .justify_between()
4525                                                .gap_2()
4526                                                .child(Label::new("Add Context"))
4527                                                .child(Label::new("/ command").color(Color::Muted))
4528                                                .into_any()
4529                                        },
4530                                        {
4531                                            let weak_self = weak_self.clone();
4532                                            move |cx| {
4533                                                weak_self
4534                                                    .update(cx, |this, cx| {
4535                                                        if let Some(editor) =
4536                                                        &this.active_context_editor
4537                                                        {
4538                                                            editor
4539                                                                .update(cx, |this, cx| {
4540                                                                    this.slash_menu_handle
4541                                                                        .toggle(cx);
4542                                                                })
4543                                                                .ok();
4544                                                        }
4545                                                    })
4546                                                    .ok();
4547                                            }
4548                                        },
4549                                    )
4550                                    .action("Add Selection", QuoteSelection.boxed_clone())
4551                            }))
4552                        }
4553                    }),
4554            );
4555
4556        h_flex()
4557            .size_full()
4558            .gap_2()
4559            .justify_between()
4560            .child(left_side)
4561            .child(right_side)
4562    }
4563}
4564
4565impl ToolbarItemView for ContextEditorToolbarItem {
4566    fn set_active_pane_item(
4567        &mut self,
4568        active_pane_item: Option<&dyn ItemHandle>,
4569        cx: &mut ViewContext<Self>,
4570    ) -> ToolbarItemLocation {
4571        self.active_context_editor = active_pane_item
4572            .and_then(|item| item.act_as::<ContextEditor>(cx))
4573            .map(|editor| editor.downgrade());
4574        cx.notify();
4575        if self.active_context_editor.is_none() {
4576            ToolbarItemLocation::Hidden
4577        } else {
4578            ToolbarItemLocation::PrimaryRight
4579        }
4580    }
4581
4582    fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
4583        cx.notify();
4584    }
4585}
4586
4587impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
4588
4589enum ContextEditorToolbarItemEvent {
4590    RegenerateSummary,
4591}
4592impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
4593
4594pub struct ContextHistory {
4595    picker: View<Picker<SavedContextPickerDelegate>>,
4596    _subscriptions: Vec<Subscription>,
4597    assistant_panel: WeakView<AssistantPanel>,
4598}
4599
4600impl ContextHistory {
4601    fn new(
4602        project: Model<Project>,
4603        context_store: Model<ContextStore>,
4604        assistant_panel: WeakView<AssistantPanel>,
4605        cx: &mut ViewContext<Self>,
4606    ) -> Self {
4607        let picker = cx.new_view(|cx| {
4608            Picker::uniform_list(
4609                SavedContextPickerDelegate::new(project, context_store.clone()),
4610                cx,
4611            )
4612            .modal(false)
4613            .max_height(None)
4614        });
4615
4616        let _subscriptions = vec![
4617            cx.observe(&context_store, |this, _, cx| {
4618                this.picker.update(cx, |picker, cx| picker.refresh(cx));
4619            }),
4620            cx.subscribe(&picker, Self::handle_picker_event),
4621        ];
4622
4623        Self {
4624            picker,
4625            _subscriptions,
4626            assistant_panel,
4627        }
4628    }
4629
4630    fn handle_picker_event(
4631        &mut self,
4632        _: View<Picker<SavedContextPickerDelegate>>,
4633        event: &SavedContextPickerEvent,
4634        cx: &mut ViewContext<Self>,
4635    ) {
4636        let SavedContextPickerEvent::Confirmed(context) = event;
4637        self.assistant_panel
4638            .update(cx, |assistant_panel, cx| match context {
4639                ContextMetadata::Remote(metadata) => {
4640                    assistant_panel
4641                        .open_remote_context(metadata.id.clone(), cx)
4642                        .detach_and_log_err(cx);
4643                }
4644                ContextMetadata::Saved(metadata) => {
4645                    assistant_panel
4646                        .open_saved_context(metadata.path.clone(), cx)
4647                        .detach_and_log_err(cx);
4648                }
4649            })
4650            .ok();
4651    }
4652}
4653
4654#[derive(Debug, PartialEq, Eq, Clone, Copy)]
4655pub enum WorkflowAssistStatus {
4656    Pending,
4657    Confirmed,
4658    Done,
4659    Idle,
4660}
4661
4662impl Render for ContextHistory {
4663    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
4664        div().size_full().child(self.picker.clone())
4665    }
4666}
4667
4668impl FocusableView for ContextHistory {
4669    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4670        self.picker.focus_handle(cx)
4671    }
4672}
4673
4674impl EventEmitter<()> for ContextHistory {}
4675
4676impl Item for ContextHistory {
4677    type Event = ();
4678
4679    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4680        Some("History".into())
4681    }
4682}
4683
4684pub struct ConfigurationView {
4685    focus_handle: FocusHandle,
4686    configuration_views: HashMap<LanguageModelProviderId, AnyView>,
4687    _registry_subscription: Subscription,
4688}
4689
4690impl ConfigurationView {
4691    fn new(cx: &mut ViewContext<Self>) -> Self {
4692        let focus_handle = cx.focus_handle();
4693
4694        let registry_subscription = cx.subscribe(
4695            &LanguageModelRegistry::global(cx),
4696            |this, _, event: &language_model::Event, cx| match event {
4697                language_model::Event::AddedProvider(provider_id) => {
4698                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
4699                    if let Some(provider) = provider {
4700                        this.add_configuration_view(&provider, cx);
4701                    }
4702                }
4703                language_model::Event::RemovedProvider(provider_id) => {
4704                    this.remove_configuration_view(provider_id);
4705                }
4706                _ => {}
4707            },
4708        );
4709
4710        let mut this = Self {
4711            focus_handle,
4712            configuration_views: HashMap::default(),
4713            _registry_subscription: registry_subscription,
4714        };
4715        this.build_configuration_views(cx);
4716        this
4717    }
4718
4719    fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
4720        let providers = LanguageModelRegistry::read_global(cx).providers();
4721        for provider in providers {
4722            self.add_configuration_view(&provider, cx);
4723        }
4724    }
4725
4726    fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
4727        self.configuration_views.remove(provider_id);
4728    }
4729
4730    fn add_configuration_view(
4731        &mut self,
4732        provider: &Arc<dyn LanguageModelProvider>,
4733        cx: &mut ViewContext<Self>,
4734    ) {
4735        let configuration_view = provider.configuration_view(cx);
4736        self.configuration_views
4737            .insert(provider.id(), configuration_view);
4738    }
4739
4740    fn render_provider_view(
4741        &mut self,
4742        provider: &Arc<dyn LanguageModelProvider>,
4743        cx: &mut ViewContext<Self>,
4744    ) -> Div {
4745        let provider_id = provider.id().0.clone();
4746        let provider_name = provider.name().0.clone();
4747        let configuration_view = self.configuration_views.get(&provider.id()).cloned();
4748
4749        let open_new_context = cx.listener({
4750            let provider = provider.clone();
4751            move |_, _, cx| {
4752                cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
4753                    provider.clone(),
4754                ))
4755            }
4756        });
4757
4758        v_flex()
4759            .gap_2()
4760            .child(
4761                h_flex()
4762                    .justify_between()
4763                    .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
4764                    .when(provider.is_authenticated(cx), move |this| {
4765                        this.child(
4766                            h_flex().justify_end().child(
4767                                Button::new(
4768                                    SharedString::from(format!("new-context-{provider_id}")),
4769                                    "Open new context",
4770                                )
4771                                .icon_position(IconPosition::Start)
4772                                .icon(IconName::Plus)
4773                                .style(ButtonStyle::Filled)
4774                                .layer(ElevationIndex::ModalSurface)
4775                                .on_click(open_new_context),
4776                            ),
4777                        )
4778                    }),
4779            )
4780            .child(
4781                div()
4782                    .p(Spacing::Large.rems(cx))
4783                    .bg(cx.theme().colors().surface_background)
4784                    .border_1()
4785                    .border_color(cx.theme().colors().border_variant)
4786                    .rounded_md()
4787                    .when(configuration_view.is_none(), |this| {
4788                        this.child(div().child(Label::new(format!(
4789                            "No configuration view for {}",
4790                            provider_name
4791                        ))))
4792                    })
4793                    .when_some(configuration_view, |this, configuration_view| {
4794                        this.child(configuration_view)
4795                    }),
4796            )
4797    }
4798}
4799
4800impl Render for ConfigurationView {
4801    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4802        let providers = LanguageModelRegistry::read_global(cx).providers();
4803        let provider_views = providers
4804            .into_iter()
4805            .map(|provider| self.render_provider_view(&provider, cx))
4806            .collect::<Vec<_>>();
4807
4808        let mut element = v_flex()
4809            .id("assistant-configuration-view")
4810            .track_focus(&self.focus_handle(cx))
4811            .bg(cx.theme().colors().editor_background)
4812            .size_full()
4813            .overflow_y_scroll()
4814            .child(
4815                v_flex()
4816                    .p(Spacing::XXLarge.rems(cx))
4817                    .border_b_1()
4818                    .border_color(cx.theme().colors().border)
4819                    .gap_1()
4820                    .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
4821                    .child(
4822                        Label::new(
4823                            "At least one LLM provider must be configured to use the Assistant.",
4824                        )
4825                        .color(Color::Muted),
4826                    ),
4827            )
4828            .child(
4829                v_flex()
4830                    .p(Spacing::XXLarge.rems(cx))
4831                    .mt_1()
4832                    .gap_6()
4833                    .flex_1()
4834                    .children(provider_views),
4835            )
4836            .into_any();
4837
4838        // We use a canvas here to get scrolling to work in the ConfigurationView. It's a workaround
4839        // because we couldn't the element to take up the size of the parent.
4840        canvas(
4841            move |bounds, cx| {
4842                element.prepaint_as_root(bounds.origin, bounds.size.into(), cx);
4843                element
4844            },
4845            |_, mut element, cx| {
4846                element.paint(cx);
4847            },
4848        )
4849        .flex_1()
4850        .w_full()
4851    }
4852}
4853
4854pub enum ConfigurationViewEvent {
4855    NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
4856}
4857
4858impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
4859
4860impl FocusableView for ConfigurationView {
4861    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
4862        self.focus_handle.clone()
4863    }
4864}
4865
4866impl Item for ConfigurationView {
4867    type Event = ConfigurationViewEvent;
4868
4869    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4870        Some("Configuration".into())
4871    }
4872}
4873
4874type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
4875
4876fn render_slash_command_output_toggle(
4877    row: MultiBufferRow,
4878    is_folded: bool,
4879    fold: ToggleFold,
4880    _cx: &mut WindowContext,
4881) -> AnyElement {
4882    Disclosure::new(
4883        ("slash-command-output-fold-indicator", row.0 as u64),
4884        !is_folded,
4885    )
4886    .selected(is_folded)
4887    .on_click(move |_e, cx| fold(!is_folded, cx))
4888    .into_any_element()
4889}
4890
4891fn fold_toggle(
4892    name: &'static str,
4893) -> impl Fn(
4894    MultiBufferRow,
4895    bool,
4896    Arc<dyn Fn(bool, &mut WindowContext<'_>) + Send + Sync>,
4897    &mut WindowContext<'_>,
4898) -> AnyElement {
4899    move |row, is_folded, fold, _cx| {
4900        Disclosure::new((name, row.0 as u64), !is_folded)
4901            .selected(is_folded)
4902            .on_click(move |_e, cx| fold(!is_folded, cx))
4903            .into_any_element()
4904    }
4905}
4906
4907fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) -> FoldPlaceholder {
4908    FoldPlaceholder {
4909        render: Arc::new({
4910            move |fold_id, fold_range, _cx| {
4911                let editor = editor.clone();
4912                ButtonLike::new(fold_id)
4913                    .style(ButtonStyle::Filled)
4914                    .layer(ElevationIndex::ElevatedSurface)
4915                    .child(Icon::new(IconName::TextSnippet))
4916                    .child(Label::new(title.clone()).single_line())
4917                    .on_click(move |_, cx| {
4918                        editor
4919                            .update(cx, |editor, cx| {
4920                                let buffer_start = fold_range
4921                                    .start
4922                                    .to_point(&editor.buffer().read(cx).read(cx));
4923                                let buffer_row = MultiBufferRow(buffer_start.row);
4924                                editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4925                            })
4926                            .ok();
4927                    })
4928                    .into_any_element()
4929            }
4930        }),
4931        constrain_width: false,
4932        merge_adjacent: false,
4933    }
4934}
4935
4936fn render_quote_selection_output_toggle(
4937    row: MultiBufferRow,
4938    is_folded: bool,
4939    fold: ToggleFold,
4940    _cx: &mut WindowContext,
4941) -> AnyElement {
4942    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
4943        .selected(is_folded)
4944        .on_click(move |_e, cx| fold(!is_folded, cx))
4945        .into_any_element()
4946}
4947
4948fn render_pending_slash_command_gutter_decoration(
4949    row: MultiBufferRow,
4950    status: &PendingSlashCommandStatus,
4951    confirm_command: Arc<dyn Fn(&mut WindowContext)>,
4952) -> AnyElement {
4953    let mut icon = IconButton::new(
4954        ("slash-command-gutter-decoration", row.0),
4955        ui::IconName::TriangleRight,
4956    )
4957    .on_click(move |_e, cx| confirm_command(cx))
4958    .icon_size(ui::IconSize::Small)
4959    .size(ui::ButtonSize::None);
4960
4961    match status {
4962        PendingSlashCommandStatus::Idle => {
4963            icon = icon.icon_color(Color::Muted);
4964        }
4965        PendingSlashCommandStatus::Running { .. } => {
4966            icon = icon.selected(true);
4967        }
4968        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
4969    }
4970
4971    icon.into_any_element()
4972}
4973
4974fn render_docs_slash_command_trailer(
4975    row: MultiBufferRow,
4976    command: PendingSlashCommand,
4977    cx: &mut WindowContext,
4978) -> AnyElement {
4979    if command.arguments.is_empty() {
4980        return Empty.into_any();
4981    }
4982    let args = DocsSlashCommandArgs::parse(&command.arguments);
4983
4984    let Some(store) = args
4985        .provider()
4986        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
4987    else {
4988        return Empty.into_any();
4989    };
4990
4991    let Some(package) = args.package() else {
4992        return Empty.into_any();
4993    };
4994
4995    let mut children = Vec::new();
4996
4997    if store.is_indexing(&package) {
4998        children.push(
4999            div()
5000                .id(("crates-being-indexed", row.0))
5001                .child(Icon::new(IconName::ArrowCircle).with_animation(
5002                    "arrow-circle",
5003                    Animation::new(Duration::from_secs(4)).repeat(),
5004                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
5005                ))
5006                .tooltip({
5007                    let package = package.clone();
5008                    move |cx| Tooltip::text(format!("Indexing {package}"), cx)
5009                })
5010                .into_any_element(),
5011        );
5012    }
5013
5014    if let Some(latest_error) = store.latest_error_for_package(&package) {
5015        children.push(
5016            div()
5017                .id(("latest-error", row.0))
5018                .child(
5019                    Icon::new(IconName::Warning)
5020                        .size(IconSize::Small)
5021                        .color(Color::Warning),
5022                )
5023                .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
5024                .into_any_element(),
5025        )
5026    }
5027
5028    let is_indexing = store.is_indexing(&package);
5029    let latest_error = store.latest_error_for_package(&package);
5030
5031    if !is_indexing && latest_error.is_none() {
5032        return Empty.into_any();
5033    }
5034
5035    h_flex().gap_2().children(children).into_any_element()
5036}
5037
5038fn make_lsp_adapter_delegate(
5039    project: &Model<Project>,
5040    cx: &mut AppContext,
5041) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
5042    project.update(cx, |project, cx| {
5043        // TODO: Find the right worktree.
5044        let Some(worktree) = project.worktrees(cx).next() else {
5045            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
5046        };
5047        let http_client = project.client().http_client().clone();
5048        project.lsp_store().update(cx, |lsp_store, cx| {
5049            Ok(Some(LocalLspAdapterDelegate::new(
5050                lsp_store,
5051                &worktree,
5052                http_client,
5053                project.fs().clone(),
5054                cx,
5055            ) as Arc<dyn LspAdapterDelegate>))
5056        })
5057    })
5058}
5059
5060fn slash_command_error_block_renderer(message: String) -> RenderBlock {
5061    Box::new(move |_| {
5062        div()
5063            .pl_6()
5064            .child(
5065                Label::new(format!("error: {}", message))
5066                    .single_line()
5067                    .color(Color::Error),
5068            )
5069            .into_any()
5070    })
5071}
5072
5073enum TokenState {
5074    NoTokensLeft {
5075        max_token_count: usize,
5076        token_count: usize,
5077    },
5078    HasMoreTokens {
5079        max_token_count: usize,
5080        token_count: usize,
5081        over_warn_threshold: bool,
5082    },
5083}
5084
5085fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
5086    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
5087
5088    let model = LanguageModelRegistry::read_global(cx).active_model()?;
5089    let token_count = context.read(cx).token_count()?;
5090    let max_token_count = model.max_token_count();
5091
5092    let remaining_tokens = max_token_count as isize - token_count as isize;
5093    let token_state = if remaining_tokens <= 0 {
5094        TokenState::NoTokensLeft {
5095            max_token_count,
5096            token_count,
5097        }
5098    } else {
5099        let over_warn_threshold =
5100            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
5101        TokenState::HasMoreTokens {
5102            max_token_count,
5103            token_count,
5104            over_warn_threshold,
5105        }
5106    };
5107    Some(token_state)
5108}
5109
5110fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
5111    let image_size = data
5112        .size(0)
5113        .map(|dimension| Pixels::from(u32::from(dimension)));
5114    let image_ratio = image_size.width / image_size.height;
5115    let bounds_ratio = max_size.width / max_size.height;
5116
5117    if image_size.width > max_size.width || image_size.height > max_size.height {
5118        if bounds_ratio > image_ratio {
5119            size(
5120                image_size.width * (max_size.height / image_size.height),
5121                max_size.height,
5122            )
5123        } else {
5124            size(
5125                max_size.width,
5126                image_size.height * (max_size.width / image_size.width),
5127            )
5128        }
5129    } else {
5130        size(image_size.width, image_size.height)
5131    }
5132}
5133
5134enum ConfigurationError {
5135    NoProvider,
5136    ProviderNotAuthenticated,
5137}
5138
5139fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
5140    let provider = LanguageModelRegistry::read_global(cx).active_provider();
5141    let is_authenticated = provider
5142        .as_ref()
5143        .map_or(false, |provider| provider.is_authenticated(cx));
5144
5145    if provider.is_some() && is_authenticated {
5146        return None;
5147    }
5148
5149    if provider.is_none() {
5150        return Some(ConfigurationError::NoProvider);
5151    }
5152
5153    if !is_authenticated {
5154        return Some(ConfigurationError::ProviderNotAuthenticated);
5155    }
5156
5157    None
5158}
5159
5160#[cfg(test)]
5161mod tests {
5162    use super::*;
5163    use gpui::{AppContext, Context};
5164    use language::Buffer;
5165    use unindent::Unindent;
5166
5167    #[gpui::test]
5168    fn test_find_code_blocks(cx: &mut AppContext) {
5169        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
5170
5171        let buffer = cx.new_model(|cx| {
5172            let text = r#"
5173                line 0
5174                line 1
5175                ```rust
5176                fn main() {}
5177                ```
5178                line 5
5179                line 6
5180                line 7
5181                ```go
5182                func main() {}
5183                ```
5184                line 11
5185                ```
5186                this is plain text code block
5187                ```
5188
5189                ```go
5190                func another() {}
5191                ```
5192                line 19
5193            "#
5194            .unindent();
5195            let mut buffer = Buffer::local(text, cx);
5196            buffer.set_language(Some(markdown.clone()), cx);
5197            buffer
5198        });
5199        let snapshot = buffer.read(cx).snapshot();
5200
5201        let code_blocks = vec![
5202            Point::new(3, 0)..Point::new(4, 0),
5203            Point::new(9, 0)..Point::new(10, 0),
5204            Point::new(13, 0)..Point::new(14, 0),
5205            Point::new(17, 0)..Point::new(18, 0),
5206        ]
5207        .into_iter()
5208        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
5209        .collect::<Vec<_>>();
5210
5211        let expected_results = vec![
5212            (0, None),
5213            (1, None),
5214            (2, Some(code_blocks[0].clone())),
5215            (3, Some(code_blocks[0].clone())),
5216            (4, Some(code_blocks[0].clone())),
5217            (5, None),
5218            (6, None),
5219            (7, None),
5220            (8, Some(code_blocks[1].clone())),
5221            (9, Some(code_blocks[1].clone())),
5222            (10, Some(code_blocks[1].clone())),
5223            (11, None),
5224            (12, Some(code_blocks[2].clone())),
5225            (13, Some(code_blocks[2].clone())),
5226            (14, Some(code_blocks[2].clone())),
5227            (15, None),
5228            (16, Some(code_blocks[3].clone())),
5229            (17, Some(code_blocks[3].clone())),
5230            (18, Some(code_blocks[3].clone())),
5231            (19, None),
5232        ];
5233
5234        for (row, expected) in expected_results {
5235            let offset = snapshot.point_to_offset(Point::new(row, 0));
5236            let range = find_surrounding_code_block(&snapshot, offset);
5237            assert_eq!(range, expected, "unexpected result on row {:?}", row);
5238        }
5239    }
5240}