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, InlineAssistant, InsertDraggedFiles, InsertIntoEditor,
  17    Message, MessageId, MessageMetadata, MessageStatus, ModelPickerDelegate, ModelSelector,
  18    NewContext, PendingSlashCommand, PendingSlashCommandStatus, QuoteSelection,
  19    RemoteContextMetadata, SavedContextMetadata, Split, ToggleFocus, ToggleModelSelector,
  20};
  21use anyhow::Result;
  22use assistant_slash_command::{SlashCommand, SlashCommandOutputSection};
  23use assistant_tool::ToolRegistry;
  24use client::{proto, zed_urls, Client, Status};
  25use collections::{BTreeSet, HashMap, HashSet};
  26use editor::{
  27    actions::{FoldAt, MoveToEndOfLine, Newline, ShowCompletions, UnfoldAt},
  28    display_map::{
  29        BlockContext, BlockDisposition, BlockId, BlockProperties, BlockStyle, Crease,
  30        CreaseMetadata, CustomBlockId, FoldId, RenderBlock, ToDisplayPoint,
  31    },
  32    scroll::{Autoscroll, AutoscrollStrategy},
  33    Anchor, Editor, EditorEvent, ProposedChangeLocation, ProposedChangesEditor, RowExt,
  34    ToOffset as _, ToPoint,
  35};
  36use editor::{display_map::CreaseId, FoldPlaceholder};
  37use fs::Fs;
  38use futures::FutureExt;
  39use gpui::{
  40    canvas, div, img, percentage, point, pulsating_between, size, Action, Animation, AnimationExt,
  41    AnyElement, AnyView, AppContext, AsyncWindowContext, ClipboardEntry, ClipboardItem,
  42    CursorStyle, Empty, Entity, EventEmitter, ExternalPaths, FocusHandle, FocusableView,
  43    FontWeight, InteractiveElement, IntoElement, Model, ParentElement, Pixels, Render, RenderImage,
  44    SharedString, Size, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
  45    UpdateGlobal, View, VisualContext, WeakView, WindowContext,
  46};
  47use indexed_docs::IndexedDocsStore;
  48use language::{
  49    language_settings::SoftWrap, BufferSnapshot, LanguageRegistry, LspAdapterDelegate, ToOffset,
  50};
  51use language_model::{
  52    provider::cloud::PROVIDER_ID, LanguageModelProvider, LanguageModelProviderId,
  53    LanguageModelRegistry, Role,
  54};
  55use language_model::{LanguageModelImage, LanguageModelToolUse};
  56use multi_buffer::MultiBufferRow;
  57use picker::{Picker, PickerDelegate};
  58use project::lsp_store::LocalLspAdapterDelegate;
  59use project::{Project, Worktree};
  60use rope::Point;
  61use search::{buffer_search::DivRegistrar, BufferSearchBar};
  62use serde::{Deserialize, Serialize};
  63use settings::{update_settings_file, Settings};
  64use smol::stream::StreamExt;
  65use std::{
  66    borrow::Cow,
  67    cmp,
  68    ops::{ControlFlow, Range},
  69    path::PathBuf,
  70    sync::Arc,
  71    time::Duration,
  72};
  73use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
  74use text::SelectionGoal;
  75use ui::TintColor;
  76use ui::{
  77    prelude::*,
  78    utils::{format_distance_from_now, DateTimeType},
  79    Avatar, ButtonLike, ContextMenu, Disclosure, ElevationIndex, KeyBinding, ListItem,
  80    ListItemSpacing, PopoverMenu, PopoverMenuHandle, 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() && project.dev_server_project_id().is_none() {
 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    PaymentRequired,
1465    MaxMonthlySpendReached,
1466    Message(SharedString),
1467}
1468
1469pub struct ContextEditor {
1470    context: Model<Context>,
1471    fs: Arc<dyn Fs>,
1472    workspace: WeakView<Workspace>,
1473    project: Model<Project>,
1474    lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1475    editor: View<Editor>,
1476    blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
1477    image_blocks: HashSet<CustomBlockId>,
1478    scroll_position: Option<ScrollPosition>,
1479    remote_id: Option<workspace::ViewId>,
1480    pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
1481    pending_slash_command_blocks: HashMap<Range<language::Anchor>, CustomBlockId>,
1482    pending_tool_use_creases: HashMap<Range<language::Anchor>, CreaseId>,
1483    _subscriptions: Vec<Subscription>,
1484    patches: HashMap<Range<language::Anchor>, PatchViewState>,
1485    active_patch: Option<Range<language::Anchor>>,
1486    assistant_panel: WeakView<AssistantPanel>,
1487    last_error: Option<AssistError>,
1488    show_accept_terms: bool,
1489    pub(crate) slash_menu_handle:
1490        PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
1491    // dragged_file_worktrees is used to keep references to worktrees that were added
1492    // when the user drag/dropped an external file onto the context editor. Since
1493    // the worktree is not part of the project panel, it would be dropped as soon as
1494    // the file is opened. In order to keep the worktree alive for the duration of the
1495    // context editor, we keep a reference here.
1496    dragged_file_worktrees: Vec<Model<Worktree>>,
1497}
1498
1499const DEFAULT_TAB_TITLE: &str = "New Context";
1500const MAX_TAB_TITLE_LEN: usize = 16;
1501
1502impl ContextEditor {
1503    fn for_context(
1504        context: Model<Context>,
1505        fs: Arc<dyn Fs>,
1506        workspace: WeakView<Workspace>,
1507        project: Model<Project>,
1508        lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1509        assistant_panel: WeakView<AssistantPanel>,
1510        cx: &mut ViewContext<Self>,
1511    ) -> Self {
1512        let completion_provider = SlashCommandCompletionProvider::new(
1513            Some(cx.view().downgrade()),
1514            Some(workspace.clone()),
1515        );
1516
1517        let editor = cx.new_view(|cx| {
1518            let mut editor = Editor::for_buffer(context.read(cx).buffer().clone(), None, cx);
1519            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
1520            editor.set_show_line_numbers(false, cx);
1521            editor.set_show_git_diff_gutter(false, cx);
1522            editor.set_show_code_actions(false, cx);
1523            editor.set_show_runnables(false, cx);
1524            editor.set_show_wrap_guides(false, cx);
1525            editor.set_show_indent_guides(false, cx);
1526            editor.set_completion_provider(Some(Box::new(completion_provider)));
1527            editor.set_collaboration_hub(Box::new(project.clone()));
1528            editor
1529        });
1530
1531        let _subscriptions = vec![
1532            cx.observe(&context, |_, _, cx| cx.notify()),
1533            cx.subscribe(&context, Self::handle_context_event),
1534            cx.subscribe(&editor, Self::handle_editor_event),
1535            cx.subscribe(&editor, Self::handle_editor_search_event),
1536        ];
1537
1538        let sections = context.read(cx).slash_command_output_sections().to_vec();
1539        let patch_ranges = context.read(cx).patch_ranges().collect::<Vec<_>>();
1540        let mut this = Self {
1541            context,
1542            editor,
1543            lsp_adapter_delegate,
1544            blocks: Default::default(),
1545            image_blocks: Default::default(),
1546            scroll_position: None,
1547            remote_id: None,
1548            fs,
1549            workspace,
1550            project,
1551            pending_slash_command_creases: HashMap::default(),
1552            pending_slash_command_blocks: HashMap::default(),
1553            pending_tool_use_creases: HashMap::default(),
1554            _subscriptions,
1555            patches: HashMap::default(),
1556            active_patch: None,
1557            assistant_panel,
1558            last_error: None,
1559            show_accept_terms: false,
1560            slash_menu_handle: Default::default(),
1561            dragged_file_worktrees: Vec::new(),
1562        };
1563        this.update_message_headers(cx);
1564        this.update_image_blocks(cx);
1565        this.insert_slash_command_output_sections(sections, false, cx);
1566        this.patches_updated(&Vec::new(), &patch_ranges, cx);
1567        this
1568    }
1569
1570    fn insert_default_prompt(&mut self, cx: &mut ViewContext<Self>) {
1571        let command_name = DefaultSlashCommand.name();
1572        self.editor.update(cx, |editor, cx| {
1573            editor.insert(&format!("/{command_name}\n\n"), cx)
1574        });
1575        let command = self.context.update(cx, |context, cx| {
1576            context.reparse(cx);
1577            context.pending_slash_commands()[0].clone()
1578        });
1579        self.run_command(
1580            command.source_range,
1581            &command.name,
1582            &command.arguments,
1583            false,
1584            false,
1585            self.workspace.clone(),
1586            cx,
1587        );
1588    }
1589
1590    fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
1591        let provider = LanguageModelRegistry::read_global(cx).active_provider();
1592        if provider
1593            .as_ref()
1594            .map_or(false, |provider| provider.must_accept_terms(cx))
1595        {
1596            self.show_accept_terms = true;
1597            cx.notify();
1598            return;
1599        }
1600
1601        if self.focus_active_patch(cx) {
1602            return;
1603        }
1604
1605        self.last_error = None;
1606        self.send_to_model(cx);
1607        cx.notify();
1608    }
1609
1610    fn focus_active_patch(&mut self, cx: &mut ViewContext<Self>) -> bool {
1611        if let Some((_range, patch)) = self.active_patch() {
1612            if let Some(editor) = patch
1613                .editor
1614                .as_ref()
1615                .and_then(|state| state.editor.upgrade())
1616            {
1617                cx.focus_view(&editor);
1618                return true;
1619            }
1620        }
1621
1622        false
1623    }
1624
1625    fn send_to_model(&mut self, cx: &mut ViewContext<Self>) {
1626        if let Some(user_message) = self.context.update(cx, |context, cx| context.assist(cx)) {
1627            let new_selection = {
1628                let cursor = user_message
1629                    .start
1630                    .to_offset(self.context.read(cx).buffer().read(cx));
1631                cursor..cursor
1632            };
1633            self.editor.update(cx, |editor, cx| {
1634                editor.change_selections(
1635                    Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
1636                    cx,
1637                    |selections| selections.select_ranges([new_selection]),
1638                );
1639            });
1640            // Avoid scrolling to the new cursor position so the assistant's output is stable.
1641            cx.defer(|this, _| this.scroll_position = None);
1642        }
1643    }
1644
1645    fn cancel(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1646        self.last_error = None;
1647
1648        if self
1649            .context
1650            .update(cx, |context, cx| context.cancel_last_assist(cx))
1651        {
1652            return;
1653        }
1654
1655        cx.propagate();
1656    }
1657
1658    fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
1659        let cursors = self.cursors(cx);
1660        self.context.update(cx, |context, cx| {
1661            let messages = context
1662                .messages_for_offsets(cursors, cx)
1663                .into_iter()
1664                .map(|message| message.id)
1665                .collect();
1666            context.cycle_message_roles(messages, cx)
1667        });
1668    }
1669
1670    fn cursors(&self, cx: &AppContext) -> Vec<usize> {
1671        let selections = self.editor.read(cx).selections.all::<usize>(cx);
1672        selections
1673            .into_iter()
1674            .map(|selection| selection.head())
1675            .collect()
1676    }
1677
1678    pub fn insert_command(&mut self, name: &str, cx: &mut ViewContext<Self>) {
1679        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1680            self.editor.update(cx, |editor, cx| {
1681                editor.transact(cx, |editor, cx| {
1682                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel());
1683                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1684                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
1685                    if newest_cursor.column > 0
1686                        || snapshot
1687                            .chars_at(newest_cursor)
1688                            .next()
1689                            .map_or(false, |ch| ch != '\n')
1690                    {
1691                        editor.move_to_end_of_line(
1692                            &MoveToEndOfLine {
1693                                stop_at_soft_wraps: false,
1694                            },
1695                            cx,
1696                        );
1697                        editor.newline(&Newline, cx);
1698                    }
1699
1700                    editor.insert(&format!("/{name}"), cx);
1701                    if command.accepts_arguments() {
1702                        editor.insert(" ", cx);
1703                        editor.show_completions(&ShowCompletions::default(), cx);
1704                    }
1705                });
1706            });
1707            if !command.requires_argument() {
1708                self.confirm_command(&ConfirmCommand, cx);
1709            }
1710        }
1711    }
1712
1713    pub fn confirm_command(&mut self, _: &ConfirmCommand, cx: &mut ViewContext<Self>) {
1714        if self.editor.read(cx).has_active_completions_menu() {
1715            return;
1716        }
1717
1718        let selections = self.editor.read(cx).selections.disjoint_anchors();
1719        let mut commands_by_range = HashMap::default();
1720        let workspace = self.workspace.clone();
1721        self.context.update(cx, |context, cx| {
1722            context.reparse(cx);
1723            for selection in selections.iter() {
1724                if let Some(command) =
1725                    context.pending_command_for_position(selection.head().text_anchor, cx)
1726                {
1727                    commands_by_range
1728                        .entry(command.source_range.clone())
1729                        .or_insert_with(|| command.clone());
1730                }
1731            }
1732        });
1733
1734        if commands_by_range.is_empty() {
1735            cx.propagate();
1736        } else {
1737            for command in commands_by_range.into_values() {
1738                self.run_command(
1739                    command.source_range,
1740                    &command.name,
1741                    &command.arguments,
1742                    true,
1743                    false,
1744                    workspace.clone(),
1745                    cx,
1746                );
1747            }
1748            cx.stop_propagation();
1749        }
1750    }
1751
1752    #[allow(clippy::too_many_arguments)]
1753    pub fn run_command(
1754        &mut self,
1755        command_range: Range<language::Anchor>,
1756        name: &str,
1757        arguments: &[String],
1758        ensure_trailing_newline: bool,
1759        expand_result: bool,
1760        workspace: WeakView<Workspace>,
1761        cx: &mut ViewContext<Self>,
1762    ) {
1763        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1764            let context = self.context.read(cx);
1765            let sections = context
1766                .slash_command_output_sections()
1767                .into_iter()
1768                .filter(|section| section.is_valid(context.buffer().read(cx)))
1769                .cloned()
1770                .collect::<Vec<_>>();
1771            let snapshot = context.buffer().read(cx).snapshot();
1772            let output = command.run(
1773                arguments,
1774                &sections,
1775                snapshot,
1776                workspace,
1777                self.lsp_adapter_delegate.clone(),
1778                cx,
1779            );
1780            self.context.update(cx, |context, cx| {
1781                context.insert_command_output(
1782                    command_range,
1783                    output,
1784                    ensure_trailing_newline,
1785                    expand_result,
1786                    cx,
1787                )
1788            });
1789        }
1790    }
1791
1792    fn handle_context_event(
1793        &mut self,
1794        _: Model<Context>,
1795        event: &ContextEvent,
1796        cx: &mut ViewContext<Self>,
1797    ) {
1798        let context_editor = cx.view().downgrade();
1799
1800        match event {
1801            ContextEvent::MessagesEdited => {
1802                self.update_message_headers(cx);
1803                self.update_image_blocks(cx);
1804                self.context.update(cx, |context, cx| {
1805                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1806                });
1807            }
1808            ContextEvent::SummaryChanged => {
1809                cx.emit(EditorEvent::TitleChanged);
1810                self.context.update(cx, |context, cx| {
1811                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1812                });
1813            }
1814            ContextEvent::StreamedCompletion => {
1815                self.editor.update(cx, |editor, cx| {
1816                    if let Some(scroll_position) = self.scroll_position {
1817                        let snapshot = editor.snapshot(cx);
1818                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
1819                        let scroll_top =
1820                            cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
1821                        editor.set_scroll_position(
1822                            point(scroll_position.offset_before_cursor.x, scroll_top),
1823                            cx,
1824                        );
1825                    }
1826
1827                    let new_tool_uses = self
1828                        .context
1829                        .read(cx)
1830                        .pending_tool_uses()
1831                        .into_iter()
1832                        .filter(|tool_use| {
1833                            !self
1834                                .pending_tool_use_creases
1835                                .contains_key(&tool_use.source_range)
1836                        })
1837                        .cloned()
1838                        .collect::<Vec<_>>();
1839
1840                    let buffer = editor.buffer().read(cx).snapshot(cx);
1841                    let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
1842                    let excerpt_id = *excerpt_id;
1843
1844                    let mut buffer_rows_to_fold = BTreeSet::new();
1845
1846                    let creases = new_tool_uses
1847                        .iter()
1848                        .map(|tool_use| {
1849                            let placeholder = FoldPlaceholder {
1850                                render: render_fold_icon_button(
1851                                    cx.view().downgrade(),
1852                                    IconName::PocketKnife,
1853                                    tool_use.name.clone().into(),
1854                                ),
1855                                constrain_width: false,
1856                                merge_adjacent: false,
1857                            };
1858                            let render_trailer =
1859                                move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
1860
1861                            let start = buffer
1862                                .anchor_in_excerpt(excerpt_id, tool_use.source_range.start)
1863                                .unwrap();
1864                            let end = buffer
1865                                .anchor_in_excerpt(excerpt_id, tool_use.source_range.end)
1866                                .unwrap();
1867
1868                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1869                            buffer_rows_to_fold.insert(buffer_row);
1870
1871                            self.context.update(cx, |context, cx| {
1872                                context.insert_content(
1873                                    Content::ToolUse {
1874                                        range: tool_use.source_range.clone(),
1875                                        tool_use: LanguageModelToolUse {
1876                                            id: tool_use.id.to_string(),
1877                                            name: tool_use.name.clone(),
1878                                            input: tool_use.input.clone(),
1879                                        },
1880                                    },
1881                                    cx,
1882                                );
1883                            });
1884
1885                            Crease::new(
1886                                start..end,
1887                                placeholder,
1888                                fold_toggle("tool-use"),
1889                                render_trailer,
1890                            )
1891                        })
1892                        .collect::<Vec<_>>();
1893
1894                    let crease_ids = editor.insert_creases(creases, cx);
1895
1896                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1897                        editor.fold_at(&FoldAt { buffer_row }, cx);
1898                    }
1899
1900                    self.pending_tool_use_creases.extend(
1901                        new_tool_uses
1902                            .iter()
1903                            .map(|tool_use| tool_use.source_range.clone())
1904                            .zip(crease_ids),
1905                    );
1906                });
1907            }
1908            ContextEvent::PatchesUpdated { removed, updated } => {
1909                self.patches_updated(removed, updated, cx);
1910            }
1911            ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
1912                self.editor.update(cx, |editor, cx| {
1913                    let buffer = editor.buffer().read(cx).snapshot(cx);
1914                    let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
1915                    let excerpt_id = *excerpt_id;
1916
1917                    editor.remove_creases(
1918                        removed
1919                            .iter()
1920                            .filter_map(|range| self.pending_slash_command_creases.remove(range)),
1921                        cx,
1922                    );
1923
1924                    editor.remove_blocks(
1925                        HashSet::from_iter(
1926                            removed.iter().filter_map(|range| {
1927                                self.pending_slash_command_blocks.remove(range)
1928                            }),
1929                        ),
1930                        None,
1931                        cx,
1932                    );
1933
1934                    let crease_ids = editor.insert_creases(
1935                        updated.iter().map(|command| {
1936                            let workspace = self.workspace.clone();
1937                            let confirm_command = Arc::new({
1938                                let context_editor = context_editor.clone();
1939                                let command = command.clone();
1940                                move |cx: &mut WindowContext| {
1941                                    context_editor
1942                                        .update(cx, |context_editor, cx| {
1943                                            context_editor.run_command(
1944                                                command.source_range.clone(),
1945                                                &command.name,
1946                                                &command.arguments,
1947                                                false,
1948                                                false,
1949                                                workspace.clone(),
1950                                                cx,
1951                                            );
1952                                        })
1953                                        .ok();
1954                                }
1955                            });
1956                            let placeholder = FoldPlaceholder {
1957                                render: Arc::new(move |_, _, _| Empty.into_any()),
1958                                constrain_width: false,
1959                                merge_adjacent: false,
1960                            };
1961                            let render_toggle = {
1962                                let confirm_command = confirm_command.clone();
1963                                let command = command.clone();
1964                                move |row, _, _, _cx: &mut WindowContext| {
1965                                    render_pending_slash_command_gutter_decoration(
1966                                        row,
1967                                        &command.status,
1968                                        confirm_command.clone(),
1969                                    )
1970                                }
1971                            };
1972                            let render_trailer = {
1973                                let command = command.clone();
1974                                move |row, _unfold, cx: &mut WindowContext| {
1975                                    // TODO: In the future we should investigate how we can expose
1976                                    // this as a hook on the `SlashCommand` trait so that we don't
1977                                    // need to special-case it here.
1978                                    if command.name == DocsSlashCommand::NAME {
1979                                        return render_docs_slash_command_trailer(
1980                                            row,
1981                                            command.clone(),
1982                                            cx,
1983                                        );
1984                                    }
1985
1986                                    Empty.into_any()
1987                                }
1988                            };
1989
1990                            let start = buffer
1991                                .anchor_in_excerpt(excerpt_id, command.source_range.start)
1992                                .unwrap();
1993                            let end = buffer
1994                                .anchor_in_excerpt(excerpt_id, command.source_range.end)
1995                                .unwrap();
1996                            Crease::new(start..end, placeholder, render_toggle, render_trailer)
1997                        }),
1998                        cx,
1999                    );
2000
2001                    let block_ids = editor.insert_blocks(
2002                        updated
2003                            .iter()
2004                            .filter_map(|command| match &command.status {
2005                                PendingSlashCommandStatus::Error(error) => {
2006                                    Some((command, error.clone()))
2007                                }
2008                                _ => None,
2009                            })
2010                            .map(|(command, error_message)| BlockProperties {
2011                                style: BlockStyle::Fixed,
2012                                position: Anchor {
2013                                    buffer_id: Some(buffer_id),
2014                                    excerpt_id,
2015                                    text_anchor: command.source_range.start,
2016                                },
2017                                height: 1,
2018                                disposition: BlockDisposition::Below,
2019                                render: slash_command_error_block_renderer(error_message),
2020                                priority: 0,
2021                            }),
2022                        None,
2023                        cx,
2024                    );
2025
2026                    self.pending_slash_command_creases.extend(
2027                        updated
2028                            .iter()
2029                            .map(|command| command.source_range.clone())
2030                            .zip(crease_ids),
2031                    );
2032
2033                    self.pending_slash_command_blocks.extend(
2034                        updated
2035                            .iter()
2036                            .map(|command| command.source_range.clone())
2037                            .zip(block_ids),
2038                    );
2039                })
2040            }
2041            ContextEvent::SlashCommandFinished {
2042                output_range,
2043                sections,
2044                run_commands_in_output,
2045                expand_result,
2046            } => {
2047                self.insert_slash_command_output_sections(
2048                    sections.iter().cloned(),
2049                    *expand_result,
2050                    cx,
2051                );
2052
2053                if *run_commands_in_output {
2054                    let commands = self.context.update(cx, |context, cx| {
2055                        context.reparse(cx);
2056                        context
2057                            .pending_commands_for_range(output_range.clone(), cx)
2058                            .to_vec()
2059                    });
2060
2061                    for command in commands {
2062                        self.run_command(
2063                            command.source_range,
2064                            &command.name,
2065                            &command.arguments,
2066                            false,
2067                            false,
2068                            self.workspace.clone(),
2069                            cx,
2070                        );
2071                    }
2072                }
2073            }
2074            ContextEvent::UsePendingTools => {
2075                let pending_tool_uses = self
2076                    .context
2077                    .read(cx)
2078                    .pending_tool_uses()
2079                    .into_iter()
2080                    .filter(|tool_use| tool_use.status.is_idle())
2081                    .cloned()
2082                    .collect::<Vec<_>>();
2083
2084                for tool_use in pending_tool_uses {
2085                    let tool_registry = ToolRegistry::global(cx);
2086                    if let Some(tool) = tool_registry.tool(&tool_use.name) {
2087                        let task = tool.run(tool_use.input, self.workspace.clone(), cx);
2088
2089                        self.context.update(cx, |context, cx| {
2090                            context.insert_tool_output(tool_use.id.clone(), task, cx);
2091                        });
2092                    }
2093                }
2094            }
2095            ContextEvent::ToolFinished {
2096                tool_use_id,
2097                output_range,
2098            } => {
2099                self.editor.update(cx, |editor, cx| {
2100                    let buffer = editor.buffer().read(cx).snapshot(cx);
2101                    let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
2102                    let excerpt_id = *excerpt_id;
2103
2104                    let placeholder = FoldPlaceholder {
2105                        render: render_fold_icon_button(
2106                            cx.view().downgrade(),
2107                            IconName::PocketKnife,
2108                            format!("Tool Result: {tool_use_id}").into(),
2109                        ),
2110                        constrain_width: false,
2111                        merge_adjacent: false,
2112                    };
2113                    let render_trailer =
2114                        move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
2115
2116                    let start = buffer
2117                        .anchor_in_excerpt(excerpt_id, output_range.start)
2118                        .unwrap();
2119                    let end = buffer
2120                        .anchor_in_excerpt(excerpt_id, output_range.end)
2121                        .unwrap();
2122
2123                    let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2124
2125                    let crease = Crease::new(
2126                        start..end,
2127                        placeholder,
2128                        fold_toggle("tool-use"),
2129                        render_trailer,
2130                    );
2131
2132                    editor.insert_creases([crease], cx);
2133                    editor.fold_at(&FoldAt { buffer_row }, cx);
2134                });
2135            }
2136            ContextEvent::Operation(_) => {}
2137            ContextEvent::ShowAssistError(error_message) => {
2138                self.last_error = Some(AssistError::Message(error_message.clone()));
2139            }
2140            ContextEvent::ShowPaymentRequiredError => {
2141                self.last_error = Some(AssistError::PaymentRequired);
2142            }
2143            ContextEvent::ShowMaxMonthlySpendReachedError => {
2144                self.last_error = Some(AssistError::MaxMonthlySpendReached);
2145            }
2146        }
2147    }
2148
2149    fn patches_updated(
2150        &mut self,
2151        removed: &Vec<Range<text::Anchor>>,
2152        updated: &Vec<Range<text::Anchor>>,
2153        cx: &mut ViewContext<ContextEditor>,
2154    ) {
2155        let this = cx.view().downgrade();
2156        let mut removed_crease_ids = Vec::new();
2157        let mut removed_block_ids = HashSet::default();
2158        let mut editors_to_close = Vec::new();
2159        for range in removed {
2160            if let Some(state) = self.patches.remove(range) {
2161                editors_to_close.extend(state.editor.and_then(|state| state.editor.upgrade()));
2162                removed_block_ids.insert(state.footer_block_id);
2163                removed_crease_ids.push(state.crease_id);
2164            }
2165        }
2166
2167        self.editor.update(cx, |editor, cx| {
2168            let snapshot = editor.snapshot(cx);
2169            let multibuffer = &snapshot.buffer_snapshot;
2170            let (&excerpt_id, _, _) = multibuffer.as_singleton().unwrap();
2171
2172            let mut replaced_blocks = HashMap::default();
2173            for range in updated {
2174                let Some(patch) = self.context.read(cx).patch_for_range(&range, cx).cloned() else {
2175                    continue;
2176                };
2177
2178                let path_count = patch.path_count();
2179                let patch_start = multibuffer
2180                    .anchor_in_excerpt(excerpt_id, patch.range.start)
2181                    .unwrap();
2182                let patch_end = multibuffer
2183                    .anchor_in_excerpt(excerpt_id, patch.range.end)
2184                    .unwrap();
2185                let render_block: RenderBlock = Box::new({
2186                    let this = this.clone();
2187                    let patch_range = range.clone();
2188                    move |cx: &mut BlockContext<'_, '_>| {
2189                        let max_width = cx.max_width;
2190                        let gutter_width = cx.gutter_dimensions.full_width();
2191                        let block_id = cx.block_id;
2192                        this.update(&mut **cx, |this, cx| {
2193                            this.render_patch_footer(
2194                                patch_range.clone(),
2195                                max_width,
2196                                gutter_width,
2197                                block_id,
2198                                cx,
2199                            )
2200                        })
2201                        .ok()
2202                        .flatten()
2203                        .unwrap_or_else(|| Empty.into_any())
2204                    }
2205                });
2206
2207                let header_placeholder = FoldPlaceholder {
2208                    render: {
2209                        let this = this.clone();
2210                        let patch_range = range.clone();
2211                        Arc::new(move |fold_id, _range, cx| {
2212                            this.update(cx, |this, cx| {
2213                                this.render_patch_header(patch_range.clone(), fold_id, cx)
2214                            })
2215                            .ok()
2216                            .flatten()
2217                            .unwrap_or_else(|| Empty.into_any())
2218                        })
2219                    },
2220                    constrain_width: false,
2221                    merge_adjacent: false,
2222                };
2223
2224                let should_refold;
2225                if let Some(state) = self.patches.get_mut(&range) {
2226                    replaced_blocks.insert(state.footer_block_id, render_block);
2227                    if let Some(editor_state) = &state.editor {
2228                        if editor_state.opened_patch != patch {
2229                            state.update_task = Some({
2230                                let this = this.clone();
2231                                cx.spawn(|_, cx| async move {
2232                                    Self::update_patch_editor(this.clone(), patch, cx)
2233                                        .await
2234                                        .log_err();
2235                                })
2236                            });
2237                        }
2238                    }
2239
2240                    should_refold =
2241                        snapshot.intersects_fold(patch_start.to_offset(&snapshot.buffer_snapshot));
2242                } else {
2243                    let block_ids = editor.insert_blocks(
2244                        [BlockProperties {
2245                            position: patch_start,
2246                            height: path_count as u32 + 1,
2247                            style: BlockStyle::Flex,
2248                            render: render_block,
2249                            disposition: BlockDisposition::Below,
2250                            priority: 0,
2251                        }],
2252                        None,
2253                        cx,
2254                    );
2255
2256                    let new_crease_ids = editor.insert_creases(
2257                        [Crease::new(
2258                            patch_start..patch_end,
2259                            header_placeholder.clone(),
2260                            fold_toggle("patch-header"),
2261                            |_, _, _| Empty.into_any_element(),
2262                        )],
2263                        cx,
2264                    );
2265
2266                    self.patches.insert(
2267                        range.clone(),
2268                        PatchViewState {
2269                            footer_block_id: block_ids[0],
2270                            crease_id: new_crease_ids[0],
2271                            editor: None,
2272                            update_task: None,
2273                        },
2274                    );
2275
2276                    should_refold = true;
2277                }
2278
2279                if should_refold {
2280                    editor.unfold_ranges([patch_start..patch_end], true, false, cx);
2281                    editor.fold_ranges([(patch_start..patch_end, header_placeholder)], false, cx);
2282                }
2283            }
2284
2285            editor.remove_creases(removed_crease_ids, cx);
2286            editor.remove_blocks(removed_block_ids, None, cx);
2287            editor.replace_blocks(replaced_blocks, None, cx);
2288        });
2289
2290        for editor in editors_to_close {
2291            self.close_patch_editor(editor, cx);
2292        }
2293
2294        self.update_active_patch(cx);
2295    }
2296
2297    fn insert_slash_command_output_sections(
2298        &mut self,
2299        sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
2300        expand_result: bool,
2301        cx: &mut ViewContext<Self>,
2302    ) {
2303        self.editor.update(cx, |editor, cx| {
2304            let buffer = editor.buffer().read(cx).snapshot(cx);
2305            let excerpt_id = *buffer.as_singleton().unwrap().0;
2306            let mut buffer_rows_to_fold = BTreeSet::new();
2307            let mut creases = Vec::new();
2308            for section in sections {
2309                let start = buffer
2310                    .anchor_in_excerpt(excerpt_id, section.range.start)
2311                    .unwrap();
2312                let end = buffer
2313                    .anchor_in_excerpt(excerpt_id, section.range.end)
2314                    .unwrap();
2315                let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2316                buffer_rows_to_fold.insert(buffer_row);
2317                creases.push(
2318                    Crease::new(
2319                        start..end,
2320                        FoldPlaceholder {
2321                            render: render_fold_icon_button(
2322                                cx.view().downgrade(),
2323                                section.icon,
2324                                section.label.clone(),
2325                            ),
2326                            constrain_width: false,
2327                            merge_adjacent: false,
2328                        },
2329                        render_slash_command_output_toggle,
2330                        |_, _, _| Empty.into_any_element(),
2331                    )
2332                    .with_metadata(CreaseMetadata {
2333                        icon: section.icon,
2334                        label: section.label,
2335                    }),
2336                );
2337            }
2338
2339            editor.insert_creases(creases, cx);
2340
2341            if expand_result {
2342                buffer_rows_to_fold.clear();
2343            }
2344            for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2345                editor.fold_at(&FoldAt { buffer_row }, cx);
2346            }
2347        });
2348    }
2349
2350    fn handle_editor_event(
2351        &mut self,
2352        _: View<Editor>,
2353        event: &EditorEvent,
2354        cx: &mut ViewContext<Self>,
2355    ) {
2356        match event {
2357            EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2358                let cursor_scroll_position = self.cursor_scroll_position(cx);
2359                if *autoscroll {
2360                    self.scroll_position = cursor_scroll_position;
2361                } else if self.scroll_position != cursor_scroll_position {
2362                    self.scroll_position = None;
2363                }
2364            }
2365            EditorEvent::SelectionsChanged { .. } => {
2366                self.scroll_position = self.cursor_scroll_position(cx);
2367                self.update_active_patch(cx);
2368            }
2369            _ => {}
2370        }
2371        cx.emit(event.clone());
2372    }
2373
2374    fn active_patch(&self) -> Option<(Range<text::Anchor>, &PatchViewState)> {
2375        let patch = self.active_patch.as_ref()?;
2376        Some((patch.clone(), self.patches.get(&patch)?))
2377    }
2378
2379    fn update_active_patch(&mut self, cx: &mut ViewContext<Self>) {
2380        let newest_cursor = self.editor.read(cx).selections.newest::<Point>(cx).head();
2381        let context = self.context.read(cx);
2382
2383        let new_patch = context.patch_containing(newest_cursor, cx).cloned();
2384
2385        if new_patch.as_ref().map(|p| &p.range) == self.active_patch.as_ref() {
2386            return;
2387        }
2388
2389        if let Some(old_patch_range) = self.active_patch.take() {
2390            if let Some(patch_state) = self.patches.get_mut(&old_patch_range) {
2391                if let Some(state) = patch_state.editor.take() {
2392                    if let Some(editor) = state.editor.upgrade() {
2393                        self.close_patch_editor(editor, cx);
2394                    }
2395                }
2396            }
2397        }
2398
2399        if let Some(new_patch) = new_patch {
2400            self.active_patch = Some(new_patch.range.clone());
2401
2402            if let Some(patch_state) = self.patches.get_mut(&new_patch.range) {
2403                let mut editor = None;
2404                if let Some(state) = &patch_state.editor {
2405                    if let Some(opened_editor) = state.editor.upgrade() {
2406                        editor = Some(opened_editor);
2407                    }
2408                }
2409
2410                if let Some(editor) = editor {
2411                    self.workspace
2412                        .update(cx, |workspace, cx| {
2413                            workspace.activate_item(&editor, true, false, cx);
2414                        })
2415                        .ok();
2416                } else {
2417                    patch_state.update_task = Some(cx.spawn(move |this, cx| async move {
2418                        Self::open_patch_editor(this, new_patch, cx).await.log_err();
2419                    }));
2420                }
2421            }
2422        }
2423    }
2424
2425    fn close_patch_editor(
2426        &mut self,
2427        editor: View<ProposedChangesEditor>,
2428        cx: &mut ViewContext<ContextEditor>,
2429    ) {
2430        self.workspace
2431            .update(cx, |workspace, cx| {
2432                if let Some(pane) = workspace.pane_for(&editor) {
2433                    pane.update(cx, |pane, cx| {
2434                        let item_id = editor.entity_id();
2435                        if !editor.read(cx).focus_handle(cx).is_focused(cx) {
2436                            pane.close_item_by_id(item_id, SaveIntent::Skip, cx)
2437                                .detach_and_log_err(cx);
2438                        }
2439                    });
2440                }
2441            })
2442            .ok();
2443    }
2444
2445    async fn open_patch_editor(
2446        this: WeakView<Self>,
2447        patch: AssistantPatch,
2448        mut cx: AsyncWindowContext,
2449    ) -> Result<()> {
2450        let project = this.update(&mut cx, |this, _| this.project.clone())?;
2451        let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2452
2453        let editor = cx.new_view(|cx| {
2454            let editor = ProposedChangesEditor::new(
2455                patch.title.clone(),
2456                resolved_patch
2457                    .edit_groups
2458                    .iter()
2459                    .map(|(buffer, groups)| ProposedChangeLocation {
2460                        buffer: buffer.clone(),
2461                        ranges: groups
2462                            .iter()
2463                            .map(|group| group.context_range.clone())
2464                            .collect(),
2465                    })
2466                    .collect(),
2467                Some(project.clone()),
2468                cx,
2469            );
2470            resolved_patch.apply(&editor, cx);
2471            editor
2472        })?;
2473
2474        this.update(&mut cx, |this, cx| {
2475            if let Some(patch_state) = this.patches.get_mut(&patch.range) {
2476                patch_state.editor = Some(PatchEditorState {
2477                    editor: editor.downgrade(),
2478                    opened_patch: patch,
2479                });
2480                patch_state.update_task.take();
2481            }
2482
2483            this.workspace
2484                .update(cx, |workspace, cx| {
2485                    workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
2486                })
2487                .log_err();
2488        })?;
2489
2490        Ok(())
2491    }
2492
2493    async fn update_patch_editor(
2494        this: WeakView<Self>,
2495        patch: AssistantPatch,
2496        mut cx: AsyncWindowContext,
2497    ) -> Result<()> {
2498        let project = this.update(&mut cx, |this, _| this.project.clone())?;
2499        let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2500        this.update(&mut cx, |this, cx| {
2501            let patch_state = this.patches.get_mut(&patch.range)?;
2502
2503            let locations = resolved_patch
2504                .edit_groups
2505                .iter()
2506                .map(|(buffer, groups)| ProposedChangeLocation {
2507                    buffer: buffer.clone(),
2508                    ranges: groups
2509                        .iter()
2510                        .map(|group| group.context_range.clone())
2511                        .collect(),
2512                })
2513                .collect();
2514
2515            if let Some(state) = &mut patch_state.editor {
2516                if let Some(editor) = state.editor.upgrade() {
2517                    editor.update(cx, |editor, cx| {
2518                        editor.set_title(patch.title.clone(), cx);
2519                        editor.reset_locations(locations, cx);
2520                        resolved_patch.apply(editor, cx);
2521                    });
2522
2523                    state.opened_patch = patch;
2524                } else {
2525                    patch_state.editor.take();
2526                }
2527            }
2528            patch_state.update_task.take();
2529
2530            Some(())
2531        })?;
2532        Ok(())
2533    }
2534
2535    fn handle_editor_search_event(
2536        &mut self,
2537        _: View<Editor>,
2538        event: &SearchEvent,
2539        cx: &mut ViewContext<Self>,
2540    ) {
2541        cx.emit(event.clone());
2542    }
2543
2544    fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2545        self.editor.update(cx, |editor, cx| {
2546            let snapshot = editor.snapshot(cx);
2547            let cursor = editor.selections.newest_anchor().head();
2548            let cursor_row = cursor
2549                .to_display_point(&snapshot.display_snapshot)
2550                .row()
2551                .as_f32();
2552            let scroll_position = editor
2553                .scroll_manager
2554                .anchor()
2555                .scroll_position(&snapshot.display_snapshot);
2556
2557            let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2558            if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2559                Some(ScrollPosition {
2560                    cursor,
2561                    offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2562                })
2563            } else {
2564                None
2565            }
2566        })
2567    }
2568
2569    fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2570        self.editor.update(cx, |editor, cx| {
2571            let buffer = editor.buffer().read(cx).snapshot(cx);
2572
2573            let excerpt_id = *buffer.as_singleton().unwrap().0;
2574            let mut old_blocks = std::mem::take(&mut self.blocks);
2575            let mut blocks_to_remove: HashMap<_, _> = old_blocks
2576                .iter()
2577                .map(|(message_id, (_, block_id))| (*message_id, *block_id))
2578                .collect();
2579            let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
2580
2581            let render_block = |message: MessageMetadata| -> RenderBlock {
2582                Box::new({
2583                    let context = self.context.clone();
2584                    move |cx| {
2585                        let message_id = MessageId(message.timestamp);
2586                        let show_spinner = message.role == Role::Assistant
2587                            && message.status == MessageStatus::Pending;
2588
2589                        let label = match message.role {
2590                            Role::User => {
2591                                Label::new("You").color(Color::Default).into_any_element()
2592                            }
2593                            Role::Assistant => {
2594                                let label = Label::new("Assistant").color(Color::Info);
2595                                if show_spinner {
2596                                    label
2597                                        .with_animation(
2598                                            "pulsating-label",
2599                                            Animation::new(Duration::from_secs(2))
2600                                                .repeat()
2601                                                .with_easing(pulsating_between(0.4, 0.8)),
2602                                            |label, delta| label.alpha(delta),
2603                                        )
2604                                        .into_any_element()
2605                                } else {
2606                                    label.into_any_element()
2607                                }
2608                            }
2609
2610                            Role::System => Label::new("System")
2611                                .color(Color::Warning)
2612                                .into_any_element(),
2613                        };
2614
2615                        let sender = ButtonLike::new("role")
2616                            .style(ButtonStyle::Filled)
2617                            .child(label)
2618                            .tooltip(|cx| {
2619                                Tooltip::with_meta(
2620                                    "Toggle message role",
2621                                    None,
2622                                    "Available roles: You (User), Assistant, System",
2623                                    cx,
2624                                )
2625                            })
2626                            .on_click({
2627                                let context = context.clone();
2628                                move |_, cx| {
2629                                    context.update(cx, |context, cx| {
2630                                        context.cycle_message_roles(
2631                                            HashSet::from_iter(Some(message_id)),
2632                                            cx,
2633                                        )
2634                                    })
2635                                }
2636                            });
2637
2638                        h_flex()
2639                            .id(("message_header", message_id.as_u64()))
2640                            .pl(cx.gutter_dimensions.full_width())
2641                            .h_11()
2642                            .w_full()
2643                            .relative()
2644                            .gap_1()
2645                            .child(sender)
2646                            .children(match &message.cache {
2647                                Some(cache) if cache.is_final_anchor => match cache.status {
2648                                    CacheStatus::Cached => Some(
2649                                        div()
2650                                            .id("cached")
2651                                            .child(
2652                                                Icon::new(IconName::DatabaseZap)
2653                                                    .size(IconSize::XSmall)
2654                                                    .color(Color::Hint),
2655                                            )
2656                                            .tooltip(|cx| {
2657                                                Tooltip::with_meta(
2658                                                    "Context cached",
2659                                                    None,
2660                                                    "Large messages cached to optimize performance",
2661                                                    cx,
2662                                                )
2663                                            })
2664                                            .into_any_element(),
2665                                    ),
2666                                    CacheStatus::Pending => Some(
2667                                        div()
2668                                            .child(
2669                                                Icon::new(IconName::Ellipsis)
2670                                                    .size(IconSize::XSmall)
2671                                                    .color(Color::Hint),
2672                                            )
2673                                            .into_any_element(),
2674                                    ),
2675                                },
2676                                _ => None,
2677                            })
2678                            .children(match &message.status {
2679                                MessageStatus::Error(error) => Some(
2680                                    Button::new("show-error", "Error")
2681                                        .color(Color::Error)
2682                                        .selected_label_color(Color::Error)
2683                                        .selected_icon_color(Color::Error)
2684                                        .icon(IconName::XCircle)
2685                                        .icon_color(Color::Error)
2686                                        .icon_size(IconSize::Small)
2687                                        .icon_position(IconPosition::Start)
2688                                        .tooltip(move |cx| {
2689                                            Tooltip::with_meta(
2690                                                "Error interacting with language model",
2691                                                None,
2692                                                "Click for more details",
2693                                                cx,
2694                                            )
2695                                        })
2696                                        .on_click({
2697                                            let context = context.clone();
2698                                            let error = error.clone();
2699                                            move |_, cx| {
2700                                                context.update(cx, |_, cx| {
2701                                                    cx.emit(ContextEvent::ShowAssistError(
2702                                                        error.clone(),
2703                                                    ));
2704                                                });
2705                                            }
2706                                        })
2707                                        .into_any_element(),
2708                                ),
2709                                MessageStatus::Canceled => Some(
2710                                    ButtonLike::new("canceled")
2711                                        .child(Icon::new(IconName::XCircle).color(Color::Disabled))
2712                                        .child(
2713                                            Label::new("Canceled")
2714                                                .size(LabelSize::Small)
2715                                                .color(Color::Disabled),
2716                                        )
2717                                        .tooltip(move |cx| {
2718                                            Tooltip::with_meta(
2719                                                "Canceled",
2720                                                None,
2721                                                "Interaction with the assistant was canceled",
2722                                                cx,
2723                                            )
2724                                        })
2725                                        .into_any_element(),
2726                                ),
2727                                _ => None,
2728                            })
2729                            .into_any_element()
2730                    }
2731                })
2732            };
2733            let create_block_properties = |message: &Message| BlockProperties {
2734                position: buffer
2735                    .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
2736                    .unwrap(),
2737                height: 2,
2738                style: BlockStyle::Sticky,
2739                disposition: BlockDisposition::Above,
2740                priority: usize::MAX,
2741                render: render_block(MessageMetadata::from(message)),
2742            };
2743            let mut new_blocks = vec![];
2744            let mut block_index_to_message = vec![];
2745            for message in self.context.read(cx).messages(cx) {
2746                if let Some(_) = blocks_to_remove.remove(&message.id) {
2747                    // This is an old message that we might modify.
2748                    let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
2749                        debug_assert!(
2750                            false,
2751                            "old_blocks should contain a message_id we've just removed."
2752                        );
2753                        continue;
2754                    };
2755                    // Should we modify it?
2756                    let message_meta = MessageMetadata::from(&message);
2757                    if meta != &message_meta {
2758                        blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
2759                        *meta = message_meta;
2760                    }
2761                } else {
2762                    // This is a new message.
2763                    new_blocks.push(create_block_properties(&message));
2764                    block_index_to_message.push((message.id, MessageMetadata::from(&message)));
2765                }
2766            }
2767            editor.replace_blocks(blocks_to_replace, None, cx);
2768            editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
2769
2770            let ids = editor.insert_blocks(new_blocks, None, cx);
2771            old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
2772                |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
2773            ));
2774            self.blocks = old_blocks;
2775        });
2776    }
2777
2778    /// Returns either the selected text, or the content of the Markdown code
2779    /// block surrounding the cursor.
2780    fn get_selection_or_code_block(
2781        context_editor_view: &View<ContextEditor>,
2782        cx: &mut ViewContext<Workspace>,
2783    ) -> Option<(String, bool)> {
2784        const CODE_FENCE_DELIMITER: &'static str = "```";
2785
2786        let context_editor = context_editor_view.read(cx).editor.read(cx);
2787
2788        if context_editor.selections.newest::<Point>(cx).is_empty() {
2789            let snapshot = context_editor.buffer().read(cx).snapshot(cx);
2790            let (_, _, snapshot) = snapshot.as_singleton()?;
2791
2792            let head = context_editor.selections.newest::<Point>(cx).head();
2793            let offset = snapshot.point_to_offset(head);
2794
2795            let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
2796            let mut text = snapshot
2797                .text_for_range(surrounding_code_block_range)
2798                .collect::<String>();
2799
2800            // If there is no newline trailing the closing three-backticks, then
2801            // tree-sitter-md extends the range of the content node to include
2802            // the backticks.
2803            if text.ends_with(CODE_FENCE_DELIMITER) {
2804                text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
2805            }
2806
2807            (!text.is_empty()).then_some((text, true))
2808        } else {
2809            let anchor = context_editor.selections.newest_anchor();
2810            let text = context_editor
2811                .buffer()
2812                .read(cx)
2813                .read(cx)
2814                .text_for_range(anchor.range())
2815                .collect::<String>();
2816
2817            (!text.is_empty()).then_some((text, false))
2818        }
2819    }
2820
2821    fn insert_selection(
2822        workspace: &mut Workspace,
2823        _: &InsertIntoEditor,
2824        cx: &mut ViewContext<Workspace>,
2825    ) {
2826        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2827            return;
2828        };
2829        let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2830            return;
2831        };
2832        let Some(active_editor_view) = workspace
2833            .active_item(cx)
2834            .and_then(|item| item.act_as::<Editor>(cx))
2835        else {
2836            return;
2837        };
2838
2839        if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
2840            active_editor_view.update(cx, |editor, cx| {
2841                editor.insert(&text, cx);
2842                editor.focus(cx);
2843            })
2844        }
2845    }
2846
2847    fn copy_code(workspace: &mut Workspace, _: &CopyCode, cx: &mut ViewContext<Workspace>) {
2848        let result = maybe!({
2849            let panel = workspace.panel::<AssistantPanel>(cx)?;
2850            let context_editor_view = panel.read(cx).active_context_editor(cx)?;
2851            Self::get_selection_or_code_block(&context_editor_view, cx)
2852        });
2853        let Some((text, is_code_block)) = result else {
2854            return;
2855        };
2856
2857        cx.write_to_clipboard(ClipboardItem::new_string(text));
2858
2859        struct CopyToClipboardToast;
2860        workspace.show_toast(
2861            Toast::new(
2862                NotificationId::unique::<CopyToClipboardToast>(),
2863                format!(
2864                    "{} copied to clipboard.",
2865                    if is_code_block {
2866                        "Code block"
2867                    } else {
2868                        "Selection"
2869                    }
2870                ),
2871            )
2872            .autohide(),
2873            cx,
2874        );
2875    }
2876
2877    fn insert_dragged_files(
2878        workspace: &mut Workspace,
2879        action: &InsertDraggedFiles,
2880        cx: &mut ViewContext<Workspace>,
2881    ) {
2882        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2883            return;
2884        };
2885        let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2886            return;
2887        };
2888
2889        let project = workspace.project().clone();
2890
2891        let paths = match action {
2892            InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
2893            InsertDraggedFiles::ExternalFiles(paths) => {
2894                let tasks = paths
2895                    .clone()
2896                    .into_iter()
2897                    .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
2898                    .collect::<Vec<_>>();
2899
2900                cx.spawn(move |_, cx| async move {
2901                    let mut paths = vec![];
2902                    let mut worktrees = vec![];
2903
2904                    let opened_paths = futures::future::join_all(tasks).await;
2905                    for (worktree, project_path) in opened_paths.into_iter().flatten() {
2906                        let Ok(worktree_root_name) =
2907                            worktree.read_with(&cx, |worktree, _| worktree.root_name().to_string())
2908                        else {
2909                            continue;
2910                        };
2911
2912                        let mut full_path = PathBuf::from(worktree_root_name.clone());
2913                        full_path.push(&project_path.path);
2914                        paths.push(full_path);
2915                        worktrees.push(worktree);
2916                    }
2917
2918                    (paths, worktrees)
2919                })
2920            }
2921        };
2922
2923        cx.spawn(|_, mut cx| async move {
2924            let (paths, dragged_file_worktrees) = paths.await;
2925            let cmd_name = file_command::FileSlashCommand.name();
2926
2927            context_editor_view
2928                .update(&mut cx, |context_editor, cx| {
2929                    let file_argument = paths
2930                        .into_iter()
2931                        .map(|path| path.to_string_lossy().to_string())
2932                        .collect::<Vec<_>>()
2933                        .join(" ");
2934
2935                    context_editor.editor.update(cx, |editor, cx| {
2936                        editor.insert("\n", cx);
2937                        editor.insert(&format!("/{} {}", cmd_name, file_argument), cx);
2938                    });
2939
2940                    context_editor.confirm_command(&ConfirmCommand, cx);
2941
2942                    context_editor
2943                        .dragged_file_worktrees
2944                        .extend(dragged_file_worktrees);
2945                })
2946                .log_err();
2947        })
2948        .detach();
2949    }
2950
2951    fn quote_selection(
2952        workspace: &mut Workspace,
2953        _: &QuoteSelection,
2954        cx: &mut ViewContext<Workspace>,
2955    ) {
2956        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2957            return;
2958        };
2959        let Some(editor) = workspace
2960            .active_item(cx)
2961            .and_then(|item| item.act_as::<Editor>(cx))
2962        else {
2963            return;
2964        };
2965
2966        let mut creases = vec![];
2967        editor.update(cx, |editor, cx| {
2968            let selections = editor.selections.all_adjusted(cx);
2969            let buffer = editor.buffer().read(cx).snapshot(cx);
2970            for selection in selections {
2971                let range = editor::ToOffset::to_offset(&selection.start, &buffer)
2972                    ..editor::ToOffset::to_offset(&selection.end, &buffer);
2973                let selected_text = buffer.text_for_range(range.clone()).collect::<String>();
2974                if selected_text.is_empty() {
2975                    continue;
2976                }
2977                let start_language = buffer.language_at(range.start);
2978                let end_language = buffer.language_at(range.end);
2979                let language_name = if start_language == end_language {
2980                    start_language.map(|language| language.code_fence_block_name())
2981                } else {
2982                    None
2983                };
2984                let language_name = language_name.as_deref().unwrap_or("");
2985                let filename = buffer
2986                    .file_at(selection.start)
2987                    .map(|file| file.full_path(cx));
2988                let text = if language_name == "markdown" {
2989                    selected_text
2990                        .lines()
2991                        .map(|line| format!("> {}", line))
2992                        .collect::<Vec<_>>()
2993                        .join("\n")
2994                } else {
2995                    let start_symbols = buffer
2996                        .symbols_containing(selection.start, None)
2997                        .map(|(_, symbols)| symbols);
2998                    let end_symbols = buffer
2999                        .symbols_containing(selection.end, None)
3000                        .map(|(_, symbols)| symbols);
3001
3002                    let outline_text = if let Some((start_symbols, end_symbols)) =
3003                        start_symbols.zip(end_symbols)
3004                    {
3005                        Some(
3006                            start_symbols
3007                                .into_iter()
3008                                .zip(end_symbols)
3009                                .take_while(|(a, b)| a == b)
3010                                .map(|(a, _)| a.text)
3011                                .collect::<Vec<_>>()
3012                                .join(" > "),
3013                        )
3014                    } else {
3015                        None
3016                    };
3017
3018                    let line_comment_prefix = start_language
3019                        .and_then(|l| l.default_scope().line_comment_prefixes().first().cloned());
3020
3021                    let fence = codeblock_fence_for_path(
3022                        filename.as_deref(),
3023                        Some(selection.start.row..=selection.end.row),
3024                    );
3025
3026                    if let Some((line_comment_prefix, outline_text)) =
3027                        line_comment_prefix.zip(outline_text)
3028                    {
3029                        let breadcrumb =
3030                            format!("{line_comment_prefix}Excerpt from: {outline_text}\n");
3031                        format!("{fence}{breadcrumb}{selected_text}\n```")
3032                    } else {
3033                        format!("{fence}{selected_text}\n```")
3034                    }
3035                };
3036                let crease_title = if let Some(path) = filename {
3037                    let start_line = selection.start.row + 1;
3038                    let end_line = selection.end.row + 1;
3039                    if start_line == end_line {
3040                        format!("{}, Line {}", path.display(), start_line)
3041                    } else {
3042                        format!("{}, Lines {} to {}", path.display(), start_line, end_line)
3043                    }
3044                } else {
3045                    "Quoted selection".to_string()
3046                };
3047                creases.push((text, crease_title));
3048            }
3049        });
3050        if creases.is_empty() {
3051            return;
3052        }
3053        // Activate the panel
3054        if !panel.focus_handle(cx).contains_focused(cx) {
3055            workspace.toggle_panel_focus::<AssistantPanel>(cx);
3056        }
3057
3058        panel.update(cx, |_, cx| {
3059            // Wait to create a new context until the workspace is no longer
3060            // being updated.
3061            cx.defer(move |panel, cx| {
3062                if let Some(context) = panel
3063                    .active_context_editor(cx)
3064                    .or_else(|| panel.new_context(cx))
3065                {
3066                    context.update(cx, |context, cx| {
3067                        context.editor.update(cx, |editor, cx| {
3068                            editor.insert("\n", cx);
3069                            for (text, crease_title) in creases {
3070                                let point = editor.selections.newest::<Point>(cx).head();
3071                                let start_row = MultiBufferRow(point.row);
3072
3073                                editor.insert(&text, cx);
3074
3075                                let snapshot = editor.buffer().read(cx).snapshot(cx);
3076                                let anchor_before = snapshot.anchor_after(point);
3077                                let anchor_after = editor
3078                                    .selections
3079                                    .newest_anchor()
3080                                    .head()
3081                                    .bias_left(&snapshot);
3082
3083                                editor.insert("\n", cx);
3084
3085                                let fold_placeholder = quote_selection_fold_placeholder(
3086                                    crease_title,
3087                                    cx.view().downgrade(),
3088                                );
3089                                let crease = Crease::new(
3090                                    anchor_before..anchor_after,
3091                                    fold_placeholder,
3092                                    render_quote_selection_output_toggle,
3093                                    |_, _, _| Empty.into_any(),
3094                                );
3095                                editor.insert_creases(vec![crease], cx);
3096                                editor.fold_at(
3097                                    &FoldAt {
3098                                        buffer_row: start_row,
3099                                    },
3100                                    cx,
3101                                );
3102                            }
3103                        })
3104                    });
3105                };
3106            });
3107        });
3108    }
3109
3110    fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
3111        if self.editor.read(cx).selections.count() == 1 {
3112            let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
3113            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3114                copied_text,
3115                metadata,
3116            ));
3117            cx.stop_propagation();
3118            return;
3119        }
3120
3121        cx.propagate();
3122    }
3123
3124    fn cut(&mut self, _: &editor::actions::Cut, cx: &mut ViewContext<Self>) {
3125        if self.editor.read(cx).selections.count() == 1 {
3126            let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
3127
3128            self.editor.update(cx, |editor, cx| {
3129                editor.transact(cx, |this, cx| {
3130                    this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3131                        s.select(selections);
3132                    });
3133                    this.insert("", cx);
3134                    cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3135                        copied_text,
3136                        metadata,
3137                    ));
3138                });
3139            });
3140
3141            cx.stop_propagation();
3142            return;
3143        }
3144
3145        cx.propagate();
3146    }
3147
3148    fn get_clipboard_contents(
3149        &mut self,
3150        cx: &mut ViewContext<Self>,
3151    ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
3152        let (snapshot, selection, creases) = self.editor.update(cx, |editor, cx| {
3153            let mut selection = editor.selections.newest::<Point>(cx);
3154            let snapshot = editor.buffer().read(cx).snapshot(cx);
3155
3156            let is_entire_line = selection.is_empty() || editor.selections.line_mode;
3157            if is_entire_line {
3158                selection.start = Point::new(selection.start.row, 0);
3159                selection.end =
3160                    cmp::min(snapshot.max_point(), Point::new(selection.start.row + 1, 0));
3161                selection.goal = SelectionGoal::None;
3162            }
3163
3164            let selection_start = snapshot.point_to_offset(selection.start);
3165
3166            (
3167                snapshot.clone(),
3168                selection.clone(),
3169                editor.display_map.update(cx, |display_map, cx| {
3170                    display_map
3171                        .snapshot(cx)
3172                        .crease_snapshot
3173                        .creases_in_range(
3174                            MultiBufferRow(selection.start.row)
3175                                ..MultiBufferRow(selection.end.row + 1),
3176                            &snapshot,
3177                        )
3178                        .filter_map(|crease| {
3179                            if let Some(metadata) = &crease.metadata {
3180                                let start = crease
3181                                    .range
3182                                    .start
3183                                    .to_offset(&snapshot)
3184                                    .saturating_sub(selection_start);
3185                                let end = crease
3186                                    .range
3187                                    .end
3188                                    .to_offset(&snapshot)
3189                                    .saturating_sub(selection_start);
3190
3191                                let range_relative_to_selection = start..end;
3192
3193                                if range_relative_to_selection.is_empty() {
3194                                    None
3195                                } else {
3196                                    Some(SelectedCreaseMetadata {
3197                                        range_relative_to_selection,
3198                                        crease: metadata.clone(),
3199                                    })
3200                                }
3201                            } else {
3202                                None
3203                            }
3204                        })
3205                        .collect::<Vec<_>>()
3206                }),
3207            )
3208        });
3209
3210        let selection = selection.map(|point| snapshot.point_to_offset(point));
3211        let context = self.context.read(cx);
3212
3213        let mut text = String::new();
3214        for message in context.messages(cx) {
3215            if message.offset_range.start >= selection.range().end {
3216                break;
3217            } else if message.offset_range.end >= selection.range().start {
3218                let range = cmp::max(message.offset_range.start, selection.range().start)
3219                    ..cmp::min(message.offset_range.end, selection.range().end);
3220                if !range.is_empty() {
3221                    for chunk in context.buffer().read(cx).text_for_range(range) {
3222                        text.push_str(chunk);
3223                    }
3224                    if message.offset_range.end < selection.range().end {
3225                        text.push('\n');
3226                    }
3227                }
3228            }
3229        }
3230
3231        (text, CopyMetadata { creases }, vec![selection])
3232    }
3233
3234    fn paste(&mut self, action: &editor::actions::Paste, cx: &mut ViewContext<Self>) {
3235        cx.stop_propagation();
3236
3237        let images = if let Some(item) = cx.read_from_clipboard() {
3238            item.into_entries()
3239                .filter_map(|entry| {
3240                    if let ClipboardEntry::Image(image) = entry {
3241                        Some(image)
3242                    } else {
3243                        None
3244                    }
3245                })
3246                .collect()
3247        } else {
3248            Vec::new()
3249        };
3250
3251        let metadata = if let Some(item) = cx.read_from_clipboard() {
3252            item.entries().first().and_then(|entry| {
3253                if let ClipboardEntry::String(text) = entry {
3254                    text.metadata_json::<CopyMetadata>()
3255                } else {
3256                    None
3257                }
3258            })
3259        } else {
3260            None
3261        };
3262
3263        if images.is_empty() {
3264            self.editor.update(cx, |editor, cx| {
3265                let paste_position = editor.selections.newest::<usize>(cx).head();
3266                editor.paste(action, cx);
3267
3268                if let Some(metadata) = metadata {
3269                    let buffer = editor.buffer().read(cx).snapshot(cx);
3270
3271                    let mut buffer_rows_to_fold = BTreeSet::new();
3272                    let weak_editor = cx.view().downgrade();
3273                    editor.insert_creases(
3274                        metadata.creases.into_iter().map(|metadata| {
3275                            let start = buffer.anchor_after(
3276                                paste_position + metadata.range_relative_to_selection.start,
3277                            );
3278                            let end = buffer.anchor_before(
3279                                paste_position + metadata.range_relative_to_selection.end,
3280                            );
3281
3282                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
3283                            buffer_rows_to_fold.insert(buffer_row);
3284                            Crease::new(
3285                                start..end,
3286                                FoldPlaceholder {
3287                                    constrain_width: false,
3288                                    render: render_fold_icon_button(
3289                                        weak_editor.clone(),
3290                                        metadata.crease.icon,
3291                                        metadata.crease.label.clone(),
3292                                    ),
3293                                    merge_adjacent: false,
3294                                },
3295                                render_slash_command_output_toggle,
3296                                |_, _, _| Empty.into_any(),
3297                            )
3298                            .with_metadata(metadata.crease.clone())
3299                        }),
3300                        cx,
3301                    );
3302                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
3303                        editor.fold_at(&FoldAt { buffer_row }, cx);
3304                    }
3305                }
3306            });
3307        } else {
3308            let mut image_positions = Vec::new();
3309            self.editor.update(cx, |editor, cx| {
3310                editor.transact(cx, |editor, cx| {
3311                    let edits = editor
3312                        .selections
3313                        .all::<usize>(cx)
3314                        .into_iter()
3315                        .map(|selection| (selection.start..selection.end, "\n"));
3316                    editor.edit(edits, cx);
3317
3318                    let snapshot = editor.buffer().read(cx).snapshot(cx);
3319                    for selection in editor.selections.all::<usize>(cx) {
3320                        image_positions.push(snapshot.anchor_before(selection.end));
3321                    }
3322                });
3323            });
3324
3325            self.context.update(cx, |context, cx| {
3326                for image in images {
3327                    let Some(render_image) = image.to_image_data(cx).log_err() else {
3328                        continue;
3329                    };
3330                    let image_id = image.id();
3331                    let image_task = LanguageModelImage::from_image(image, cx).shared();
3332
3333                    for image_position in image_positions.iter() {
3334                        context.insert_content(
3335                            Content::Image {
3336                                anchor: image_position.text_anchor,
3337                                image_id,
3338                                image: image_task.clone(),
3339                                render_image: render_image.clone(),
3340                            },
3341                            cx,
3342                        );
3343                    }
3344                }
3345            });
3346        }
3347    }
3348
3349    fn update_image_blocks(&mut self, cx: &mut ViewContext<Self>) {
3350        self.editor.update(cx, |editor, cx| {
3351            let buffer = editor.buffer().read(cx).snapshot(cx);
3352            let excerpt_id = *buffer.as_singleton().unwrap().0;
3353            let old_blocks = std::mem::take(&mut self.image_blocks);
3354            let new_blocks = self
3355                .context
3356                .read(cx)
3357                .contents(cx)
3358                .filter_map(|content| {
3359                    if let Content::Image {
3360                        anchor,
3361                        render_image,
3362                        ..
3363                    } = content
3364                    {
3365                        Some((anchor, render_image))
3366                    } else {
3367                        None
3368                    }
3369                })
3370                .filter_map(|(anchor, render_image)| {
3371                    const MAX_HEIGHT_IN_LINES: u32 = 8;
3372                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
3373                    let image = render_image.clone();
3374                    anchor.is_valid(&buffer).then(|| BlockProperties {
3375                        position: anchor,
3376                        height: MAX_HEIGHT_IN_LINES,
3377                        style: BlockStyle::Sticky,
3378                        render: Box::new(move |cx| {
3379                            let image_size = size_for_image(
3380                                &image,
3381                                size(
3382                                    cx.max_width - cx.gutter_dimensions.full_width(),
3383                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
3384                                ),
3385                            );
3386                            h_flex()
3387                                .pl(cx.gutter_dimensions.full_width())
3388                                .child(
3389                                    img(image.clone())
3390                                        .object_fit(gpui::ObjectFit::ScaleDown)
3391                                        .w(image_size.width)
3392                                        .h(image_size.height),
3393                                )
3394                                .into_any_element()
3395                        }),
3396
3397                        disposition: BlockDisposition::Above,
3398                        priority: 0,
3399                    })
3400                })
3401                .collect::<Vec<_>>();
3402
3403            editor.remove_blocks(old_blocks, None, cx);
3404            let ids = editor.insert_blocks(new_blocks, None, cx);
3405            self.image_blocks = HashSet::from_iter(ids);
3406        });
3407    }
3408
3409    fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
3410        self.context.update(cx, |context, cx| {
3411            let selections = self.editor.read(cx).selections.disjoint_anchors();
3412            for selection in selections.as_ref() {
3413                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
3414                let range = selection
3415                    .map(|endpoint| endpoint.to_offset(&buffer))
3416                    .range();
3417                context.split_message(range, cx);
3418            }
3419        });
3420    }
3421
3422    fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
3423        self.context.update(cx, |context, cx| {
3424            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
3425        });
3426    }
3427
3428    fn title(&self, cx: &AppContext) -> Cow<str> {
3429        self.context
3430            .read(cx)
3431            .summary()
3432            .map(|summary| summary.text.clone())
3433            .map(Cow::Owned)
3434            .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
3435    }
3436
3437    fn render_patch_header(
3438        &self,
3439        range: Range<text::Anchor>,
3440        _id: FoldId,
3441        cx: &mut ViewContext<Self>,
3442    ) -> Option<AnyElement> {
3443        let patch = self.context.read(cx).patch_for_range(&range, cx)?;
3444        let theme = cx.theme().clone();
3445        Some(
3446            h_flex()
3447                .px_1()
3448                .py_0p5()
3449                .border_b_1()
3450                .border_color(theme.status().info_border)
3451                .gap_1()
3452                .child(Icon::new(IconName::Diff).size(IconSize::Small))
3453                .child(Label::new(patch.title.clone()).size(LabelSize::Small))
3454                .into_any(),
3455        )
3456    }
3457
3458    fn render_patch_footer(
3459        &mut self,
3460        range: Range<text::Anchor>,
3461        max_width: Pixels,
3462        gutter_width: Pixels,
3463        id: BlockId,
3464        cx: &mut ViewContext<Self>,
3465    ) -> Option<AnyElement> {
3466        let snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3467        let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
3468        let excerpt_id = *excerpt_id;
3469        let anchor = snapshot
3470            .buffer_snapshot
3471            .anchor_in_excerpt(excerpt_id, range.start)
3472            .unwrap();
3473
3474        if !snapshot.intersects_fold(anchor) {
3475            return None;
3476        }
3477
3478        let patch = self.context.read(cx).patch_for_range(&range, cx)?;
3479        let paths = patch
3480            .paths()
3481            .map(|p| SharedString::from(p.to_string()))
3482            .collect::<BTreeSet<_>>();
3483
3484        Some(
3485            v_flex()
3486                .id(id)
3487                .pl(gutter_width)
3488                .w(max_width)
3489                .py_2()
3490                .cursor(CursorStyle::PointingHand)
3491                .on_click(cx.listener(move |this, _, cx| {
3492                    this.editor.update(cx, |editor, cx| {
3493                        editor.change_selections(None, cx, |selections| {
3494                            selections.select_ranges(vec![anchor..anchor]);
3495                        });
3496                    });
3497                    this.focus_active_patch(cx);
3498                }))
3499                .children(paths.into_iter().map(|path| {
3500                    h_flex()
3501                        .pl_1()
3502                        .gap_1()
3503                        .child(Icon::new(IconName::File).size(IconSize::Small))
3504                        .child(Label::new(path).size(LabelSize::Small))
3505                }))
3506                .when(patch.status == AssistantPatchStatus::Pending, |div| {
3507                    div.child(
3508                        Label::new("Generating")
3509                            .color(Color::Muted)
3510                            .size(LabelSize::Small)
3511                            .with_animation(
3512                                "pulsating-label",
3513                                Animation::new(Duration::from_secs(2))
3514                                    .repeat()
3515                                    .with_easing(pulsating_between(0.4, 1.)),
3516                                |label, delta| label.alpha(delta),
3517                            ),
3518                    )
3519                })
3520                .into_any(),
3521        )
3522    }
3523
3524    fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3525        use feature_flags::FeatureFlagAppExt;
3526        let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
3527            assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
3528        });
3529
3530        if nudge.map_or(false, |value| value) {
3531            Some(
3532                h_flex()
3533                    .p_3()
3534                    .border_b_1()
3535                    .border_color(cx.theme().colors().border_variant)
3536                    .bg(cx.theme().colors().editor_background)
3537                    .justify_between()
3538                    .child(
3539                        h_flex()
3540                            .gap_3()
3541                            .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
3542                            .child(Label::new("Zed AI is here! Get started by signing in →")),
3543                    )
3544                    .child(
3545                        Button::new("sign-in", "Sign in")
3546                            .size(ButtonSize::Compact)
3547                            .style(ButtonStyle::Filled)
3548                            .on_click(cx.listener(|this, _event, cx| {
3549                                let client = this
3550                                    .workspace
3551                                    .update(cx, |workspace, _| workspace.client().clone())
3552                                    .log_err();
3553
3554                                if let Some(client) = client {
3555                                    cx.spawn(|this, mut cx| async move {
3556                                        client.authenticate_and_connect(true, &mut cx).await?;
3557                                        this.update(&mut cx, |_, cx| cx.notify())
3558                                    })
3559                                    .detach_and_log_err(cx)
3560                                }
3561                            })),
3562                    )
3563                    .into_any_element(),
3564            )
3565        } else if let Some(configuration_error) = configuration_error(cx) {
3566            let label = match configuration_error {
3567                ConfigurationError::NoProvider => "No LLM provider selected.",
3568                ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
3569            };
3570            Some(
3571                h_flex()
3572                    .px_3()
3573                    .py_2()
3574                    .border_b_1()
3575                    .border_color(cx.theme().colors().border_variant)
3576                    .bg(cx.theme().colors().editor_background)
3577                    .justify_between()
3578                    .child(
3579                        h_flex()
3580                            .gap_3()
3581                            .child(
3582                                Icon::new(IconName::Warning)
3583                                    .size(IconSize::Small)
3584                                    .color(Color::Warning),
3585                            )
3586                            .child(Label::new(label)),
3587                    )
3588                    .child(
3589                        Button::new("open-configuration", "Configure Providers")
3590                            .size(ButtonSize::Compact)
3591                            .icon(Some(IconName::SlidersVertical))
3592                            .icon_size(IconSize::Small)
3593                            .icon_position(IconPosition::Start)
3594                            .style(ButtonStyle::Filled)
3595                            .on_click({
3596                                let focus_handle = self.focus_handle(cx).clone();
3597                                move |_event, cx| {
3598                                    focus_handle.dispatch_action(&ShowConfiguration, cx);
3599                                }
3600                            }),
3601                    )
3602                    .into_any_element(),
3603            )
3604        } else {
3605            None
3606        }
3607    }
3608
3609    fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3610        let focus_handle = self.focus_handle(cx).clone();
3611
3612        let (style, tooltip) = match token_state(&self.context, cx) {
3613            Some(TokenState::NoTokensLeft { .. }) => (
3614                ButtonStyle::Tinted(TintColor::Negative),
3615                Some(Tooltip::text("Token limit reached", cx)),
3616            ),
3617            Some(TokenState::HasMoreTokens {
3618                over_warn_threshold,
3619                ..
3620            }) => {
3621                let (style, tooltip) = if over_warn_threshold {
3622                    (
3623                        ButtonStyle::Tinted(TintColor::Warning),
3624                        Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3625                    )
3626                } else {
3627                    (ButtonStyle::Filled, None)
3628                };
3629                (style, tooltip)
3630            }
3631            None => (ButtonStyle::Filled, None),
3632        };
3633
3634        let provider = LanguageModelRegistry::read_global(cx).active_provider();
3635
3636        let has_configuration_error = configuration_error(cx).is_some();
3637        let needs_to_accept_terms = self.show_accept_terms
3638            && provider
3639                .as_ref()
3640                .map_or(false, |provider| provider.must_accept_terms(cx));
3641        let disabled = has_configuration_error || needs_to_accept_terms;
3642
3643        ButtonLike::new("send_button")
3644            .disabled(disabled)
3645            .style(style)
3646            .when_some(tooltip, |button, tooltip| {
3647                button.tooltip(move |_| tooltip.clone())
3648            })
3649            .layer(ElevationIndex::ModalSurface)
3650            .child(Label::new("Send"))
3651            .children(
3652                KeyBinding::for_action_in(&Assist, &focus_handle, cx)
3653                    .map(|binding| binding.into_any_element()),
3654            )
3655            .on_click(move |_event, cx| {
3656                focus_handle.dispatch_action(&Assist, cx);
3657            })
3658    }
3659
3660    fn render_last_error(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3661        let last_error = self.last_error.as_ref()?;
3662
3663        Some(
3664            div()
3665                .absolute()
3666                .right_3()
3667                .bottom_12()
3668                .max_w_96()
3669                .py_2()
3670                .px_3()
3671                .elevation_2(cx)
3672                .occlude()
3673                .child(match last_error {
3674                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
3675                    AssistError::MaxMonthlySpendReached => {
3676                        self.render_max_monthly_spend_reached_error(cx)
3677                    }
3678                    AssistError::Message(error_message) => {
3679                        self.render_assist_error(error_message, cx)
3680                    }
3681                })
3682                .into_any(),
3683        )
3684    }
3685
3686    fn render_payment_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3687        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.";
3688
3689        v_flex()
3690            .gap_0p5()
3691            .child(
3692                h_flex()
3693                    .gap_1p5()
3694                    .items_center()
3695                    .child(Icon::new(IconName::XCircle).color(Color::Error))
3696                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
3697            )
3698            .child(
3699                div()
3700                    .id("error-message")
3701                    .max_h_24()
3702                    .overflow_y_scroll()
3703                    .child(Label::new(ERROR_MESSAGE)),
3704            )
3705            .child(
3706                h_flex()
3707                    .justify_end()
3708                    .mt_1()
3709                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
3710                        |this, _, cx| {
3711                            this.last_error = None;
3712                            cx.open_url(&zed_urls::account_url(cx));
3713                            cx.notify();
3714                        },
3715                    )))
3716                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3717                        |this, _, cx| {
3718                            this.last_error = None;
3719                            cx.notify();
3720                        },
3721                    ))),
3722            )
3723            .into_any()
3724    }
3725
3726    fn render_max_monthly_spend_reached_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3727        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
3728
3729        v_flex()
3730            .gap_0p5()
3731            .child(
3732                h_flex()
3733                    .gap_1p5()
3734                    .items_center()
3735                    .child(Icon::new(IconName::XCircle).color(Color::Error))
3736                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
3737            )
3738            .child(
3739                div()
3740                    .id("error-message")
3741                    .max_h_24()
3742                    .overflow_y_scroll()
3743                    .child(Label::new(ERROR_MESSAGE)),
3744            )
3745            .child(
3746                h_flex()
3747                    .justify_end()
3748                    .mt_1()
3749                    .child(
3750                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
3751                            cx.listener(|this, _, cx| {
3752                                this.last_error = None;
3753                                cx.open_url(&zed_urls::account_url(cx));
3754                                cx.notify();
3755                            }),
3756                        ),
3757                    )
3758                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3759                        |this, _, cx| {
3760                            this.last_error = None;
3761                            cx.notify();
3762                        },
3763                    ))),
3764            )
3765            .into_any()
3766    }
3767
3768    fn render_assist_error(
3769        &self,
3770        error_message: &SharedString,
3771        cx: &mut ViewContext<Self>,
3772    ) -> AnyElement {
3773        v_flex()
3774            .gap_0p5()
3775            .child(
3776                h_flex()
3777                    .gap_1p5()
3778                    .items_center()
3779                    .child(Icon::new(IconName::XCircle).color(Color::Error))
3780                    .child(
3781                        Label::new("Error interacting with language model")
3782                            .weight(FontWeight::MEDIUM),
3783                    ),
3784            )
3785            .child(
3786                div()
3787                    .id("error-message")
3788                    .max_h_24()
3789                    .overflow_y_scroll()
3790                    .child(Label::new(error_message.clone())),
3791            )
3792            .child(
3793                h_flex()
3794                    .justify_end()
3795                    .mt_1()
3796                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3797                        |this, _, cx| {
3798                            this.last_error = None;
3799                            cx.notify();
3800                        },
3801                    ))),
3802            )
3803            .into_any()
3804    }
3805}
3806
3807/// Returns the contents of the *outermost* fenced code block that contains the given offset.
3808fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
3809    const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
3810    const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
3811
3812    let layer = snapshot.syntax_layers().next()?;
3813
3814    let root_node = layer.node();
3815    let mut cursor = root_node.walk();
3816
3817    // Go to the first child for the given offset
3818    while cursor.goto_first_child_for_byte(offset).is_some() {
3819        // If we're at the end of the node, go to the next one.
3820        // Example: if you have a fenced-code-block, and you're on the start of the line
3821        // right after the closing ```, you want to skip the fenced-code-block and
3822        // go to the next sibling.
3823        if cursor.node().end_byte() == offset {
3824            cursor.goto_next_sibling();
3825        }
3826
3827        if cursor.node().start_byte() > offset {
3828            break;
3829        }
3830
3831        // We found the fenced code block.
3832        if cursor.node().kind() == CODE_BLOCK_NODE {
3833            // Now we need to find the child node that contains the code.
3834            cursor.goto_first_child();
3835            loop {
3836                if cursor.node().kind() == CODE_BLOCK_CONTENT {
3837                    return Some(cursor.node().byte_range());
3838                }
3839                if !cursor.goto_next_sibling() {
3840                    break;
3841                }
3842            }
3843        }
3844    }
3845
3846    None
3847}
3848
3849fn render_fold_icon_button(
3850    editor: WeakView<Editor>,
3851    icon: IconName,
3852    label: SharedString,
3853) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut WindowContext) -> AnyElement> {
3854    Arc::new(move |fold_id, fold_range, _cx| {
3855        let editor = editor.clone();
3856        ButtonLike::new(fold_id)
3857            .style(ButtonStyle::Filled)
3858            .layer(ElevationIndex::ElevatedSurface)
3859            .child(Icon::new(icon))
3860            .child(Label::new(label.clone()).single_line())
3861            .on_click(move |_, cx| {
3862                editor
3863                    .update(cx, |editor, cx| {
3864                        let buffer_start = fold_range
3865                            .start
3866                            .to_point(&editor.buffer().read(cx).read(cx));
3867                        let buffer_row = MultiBufferRow(buffer_start.row);
3868                        editor.unfold_at(&UnfoldAt { buffer_row }, cx);
3869                    })
3870                    .ok();
3871            })
3872            .into_any_element()
3873    })
3874}
3875
3876#[derive(Debug, Clone, Serialize, Deserialize)]
3877struct CopyMetadata {
3878    creases: Vec<SelectedCreaseMetadata>,
3879}
3880
3881#[derive(Debug, Clone, Serialize, Deserialize)]
3882struct SelectedCreaseMetadata {
3883    range_relative_to_selection: Range<usize>,
3884    crease: CreaseMetadata,
3885}
3886
3887impl EventEmitter<EditorEvent> for ContextEditor {}
3888impl EventEmitter<SearchEvent> for ContextEditor {}
3889
3890impl Render for ContextEditor {
3891    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3892        let provider = LanguageModelRegistry::read_global(cx).active_provider();
3893        let accept_terms = if self.show_accept_terms {
3894            provider
3895                .as_ref()
3896                .and_then(|provider| provider.render_accept_terms(cx))
3897        } else {
3898            None
3899        };
3900        let focus_handle = self
3901            .workspace
3902            .update(cx, |workspace, cx| {
3903                Some(workspace.active_item_as::<Editor>(cx)?.focus_handle(cx))
3904            })
3905            .ok()
3906            .flatten();
3907        v_flex()
3908            .key_context("ContextEditor")
3909            .capture_action(cx.listener(ContextEditor::cancel))
3910            .capture_action(cx.listener(ContextEditor::save))
3911            .capture_action(cx.listener(ContextEditor::copy))
3912            .capture_action(cx.listener(ContextEditor::cut))
3913            .capture_action(cx.listener(ContextEditor::paste))
3914            .capture_action(cx.listener(ContextEditor::cycle_message_role))
3915            .capture_action(cx.listener(ContextEditor::confirm_command))
3916            .on_action(cx.listener(ContextEditor::assist))
3917            .on_action(cx.listener(ContextEditor::split))
3918            .size_full()
3919            .children(self.render_notice(cx))
3920            .child(
3921                div()
3922                    .flex_grow()
3923                    .bg(cx.theme().colors().editor_background)
3924                    .child(self.editor.clone()),
3925            )
3926            .when_some(accept_terms, |this, element| {
3927                this.child(
3928                    div()
3929                        .absolute()
3930                        .right_3()
3931                        .bottom_12()
3932                        .max_w_96()
3933                        .py_2()
3934                        .px_3()
3935                        .elevation_2(cx)
3936                        .bg(cx.theme().colors().surface_background)
3937                        .occlude()
3938                        .child(element),
3939                )
3940            })
3941            .children(self.render_last_error(cx))
3942            .child(
3943                h_flex().w_full().relative().child(
3944                    h_flex()
3945                        .p_2()
3946                        .w_full()
3947                        .border_t_1()
3948                        .border_color(cx.theme().colors().border_variant)
3949                        .bg(cx.theme().colors().editor_background)
3950                        .child(
3951                            h_flex()
3952                                .gap_2()
3953                                .child(render_inject_context_menu(cx.view().downgrade(), cx))
3954                                .child(
3955                                    IconButton::new("quote-button", IconName::Quote)
3956                                        .icon_size(IconSize::Small)
3957                                        .on_click(|_, cx| {
3958                                            cx.dispatch_action(QuoteSelection.boxed_clone());
3959                                        })
3960                                        .tooltip(move |cx| {
3961                                            cx.new_view(|cx| {
3962                                                Tooltip::new("Insert Selection").key_binding(
3963                                                    focus_handle.as_ref().and_then(|handle| {
3964                                                        KeyBinding::for_action_in(
3965                                                            &QuoteSelection,
3966                                                            &handle,
3967                                                            cx,
3968                                                        )
3969                                                    }),
3970                                                )
3971                                            })
3972                                            .into()
3973                                        }),
3974                                ),
3975                        )
3976                        .child(
3977                            h_flex()
3978                                .w_full()
3979                                .justify_end()
3980                                .child(div().child(self.render_send_button(cx))),
3981                        ),
3982                ),
3983            )
3984    }
3985}
3986
3987impl FocusableView for ContextEditor {
3988    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
3989        self.editor.focus_handle(cx)
3990    }
3991}
3992
3993impl Item for ContextEditor {
3994    type Event = editor::EditorEvent;
3995
3996    fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
3997        Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
3998    }
3999
4000    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
4001        match event {
4002            EditorEvent::Edited { .. } => {
4003                f(item::ItemEvent::Edit);
4004            }
4005            EditorEvent::TitleChanged => {
4006                f(item::ItemEvent::UpdateTab);
4007            }
4008            _ => {}
4009        }
4010    }
4011
4012    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
4013        Some(self.title(cx).to_string().into())
4014    }
4015
4016    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
4017        Some(Box::new(handle.clone()))
4018    }
4019
4020    fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
4021        self.editor.update(cx, |editor, cx| {
4022            Item::set_nav_history(editor, nav_history, cx)
4023        })
4024    }
4025
4026    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
4027        self.editor
4028            .update(cx, |editor, cx| Item::navigate(editor, data, cx))
4029    }
4030
4031    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
4032        self.editor.update(cx, Item::deactivated)
4033    }
4034}
4035
4036impl SearchableItem for ContextEditor {
4037    type Match = <Editor as SearchableItem>::Match;
4038
4039    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
4040        self.editor.update(cx, |editor, cx| {
4041            editor.clear_matches(cx);
4042        });
4043    }
4044
4045    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4046        self.editor
4047            .update(cx, |editor, cx| editor.update_matches(matches, cx));
4048    }
4049
4050    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
4051        self.editor
4052            .update(cx, |editor, cx| editor.query_suggestion(cx))
4053    }
4054
4055    fn activate_match(
4056        &mut self,
4057        index: usize,
4058        matches: &[Self::Match],
4059        cx: &mut ViewContext<Self>,
4060    ) {
4061        self.editor.update(cx, |editor, cx| {
4062            editor.activate_match(index, matches, cx);
4063        });
4064    }
4065
4066    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4067        self.editor
4068            .update(cx, |editor, cx| editor.select_matches(matches, cx));
4069    }
4070
4071    fn replace(
4072        &mut self,
4073        identifier: &Self::Match,
4074        query: &project::search::SearchQuery,
4075        cx: &mut ViewContext<Self>,
4076    ) {
4077        self.editor
4078            .update(cx, |editor, cx| editor.replace(identifier, query, cx));
4079    }
4080
4081    fn find_matches(
4082        &mut self,
4083        query: Arc<project::search::SearchQuery>,
4084        cx: &mut ViewContext<Self>,
4085    ) -> Task<Vec<Self::Match>> {
4086        self.editor
4087            .update(cx, |editor, cx| editor.find_matches(query, cx))
4088    }
4089
4090    fn active_match_index(
4091        &mut self,
4092        matches: &[Self::Match],
4093        cx: &mut ViewContext<Self>,
4094    ) -> Option<usize> {
4095        self.editor
4096            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
4097    }
4098}
4099
4100impl FollowableItem for ContextEditor {
4101    fn remote_id(&self) -> Option<workspace::ViewId> {
4102        self.remote_id
4103    }
4104
4105    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
4106        let context = self.context.read(cx);
4107        Some(proto::view::Variant::ContextEditor(
4108            proto::view::ContextEditor {
4109                context_id: context.id().to_proto(),
4110                editor: if let Some(proto::view::Variant::Editor(proto)) =
4111                    self.editor.read(cx).to_state_proto(cx)
4112                {
4113                    Some(proto)
4114                } else {
4115                    None
4116                },
4117            },
4118        ))
4119    }
4120
4121    fn from_state_proto(
4122        workspace: View<Workspace>,
4123        id: workspace::ViewId,
4124        state: &mut Option<proto::view::Variant>,
4125        cx: &mut WindowContext,
4126    ) -> Option<Task<Result<View<Self>>>> {
4127        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
4128            return None;
4129        };
4130        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
4131            unreachable!()
4132        };
4133
4134        let context_id = ContextId::from_proto(state.context_id);
4135        let editor_state = state.editor?;
4136
4137        let (project, panel) = workspace.update(cx, |workspace, cx| {
4138            Some((
4139                workspace.project().clone(),
4140                workspace.panel::<AssistantPanel>(cx)?,
4141            ))
4142        })?;
4143
4144        let context_editor =
4145            panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
4146
4147        Some(cx.spawn(|mut cx| async move {
4148            let context_editor = context_editor.await?;
4149            context_editor
4150                .update(&mut cx, |context_editor, cx| {
4151                    context_editor.remote_id = Some(id);
4152                    context_editor.editor.update(cx, |editor, cx| {
4153                        editor.apply_update_proto(
4154                            &project,
4155                            proto::update_view::Variant::Editor(proto::update_view::Editor {
4156                                selections: editor_state.selections,
4157                                pending_selection: editor_state.pending_selection,
4158                                scroll_top_anchor: editor_state.scroll_top_anchor,
4159                                scroll_x: editor_state.scroll_y,
4160                                scroll_y: editor_state.scroll_y,
4161                                ..Default::default()
4162                            }),
4163                            cx,
4164                        )
4165                    })
4166                })?
4167                .await?;
4168            Ok(context_editor)
4169        }))
4170    }
4171
4172    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
4173        Editor::to_follow_event(event)
4174    }
4175
4176    fn add_event_to_update_proto(
4177        &self,
4178        event: &Self::Event,
4179        update: &mut Option<proto::update_view::Variant>,
4180        cx: &WindowContext,
4181    ) -> bool {
4182        self.editor
4183            .read(cx)
4184            .add_event_to_update_proto(event, update, cx)
4185    }
4186
4187    fn apply_update_proto(
4188        &mut self,
4189        project: &Model<Project>,
4190        message: proto::update_view::Variant,
4191        cx: &mut ViewContext<Self>,
4192    ) -> Task<Result<()>> {
4193        self.editor.update(cx, |editor, cx| {
4194            editor.apply_update_proto(project, message, cx)
4195        })
4196    }
4197
4198    fn is_project_item(&self, _cx: &WindowContext) -> bool {
4199        true
4200    }
4201
4202    fn set_leader_peer_id(
4203        &mut self,
4204        leader_peer_id: Option<proto::PeerId>,
4205        cx: &mut ViewContext<Self>,
4206    ) {
4207        self.editor.update(cx, |editor, cx| {
4208            editor.set_leader_peer_id(leader_peer_id, cx)
4209        })
4210    }
4211
4212    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
4213        if existing.context.read(cx).id() == self.context.read(cx).id() {
4214            Some(item::Dedup::KeepExisting)
4215        } else {
4216            None
4217        }
4218    }
4219}
4220
4221pub struct ContextEditorToolbarItem {
4222    fs: Arc<dyn Fs>,
4223    workspace: WeakView<Workspace>,
4224    active_context_editor: Option<WeakView<ContextEditor>>,
4225    model_summary_editor: View<Editor>,
4226    model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4227}
4228
4229fn active_editor_focus_handle(
4230    workspace: &WeakView<Workspace>,
4231    cx: &WindowContext<'_>,
4232) -> Option<FocusHandle> {
4233    workspace.upgrade().and_then(|workspace| {
4234        Some(
4235            workspace
4236                .read(cx)
4237                .active_item_as::<Editor>(cx)?
4238                .focus_handle(cx),
4239        )
4240    })
4241}
4242
4243fn render_inject_context_menu(
4244    active_context_editor: WeakView<ContextEditor>,
4245    cx: &mut WindowContext<'_>,
4246) -> impl IntoElement {
4247    let commands = SlashCommandRegistry::global(cx);
4248
4249    slash_command_picker::SlashCommandSelector::new(
4250        commands.clone(),
4251        active_context_editor,
4252        IconButton::new("trigger", IconName::SlashSquare)
4253            .icon_size(IconSize::Small)
4254            .tooltip(|cx| {
4255                Tooltip::with_meta("Insert Context", None, "Type / to insert via keyboard", cx)
4256            }),
4257    )
4258}
4259
4260impl ContextEditorToolbarItem {
4261    pub fn new(
4262        workspace: &Workspace,
4263        model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4264        model_summary_editor: View<Editor>,
4265    ) -> Self {
4266        Self {
4267            fs: workspace.app_state().fs.clone(),
4268            workspace: workspace.weak_handle(),
4269            active_context_editor: None,
4270            model_summary_editor,
4271            model_selector_menu_handle,
4272        }
4273    }
4274
4275    fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
4276        let context = &self
4277            .active_context_editor
4278            .as_ref()?
4279            .upgrade()?
4280            .read(cx)
4281            .context;
4282        let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
4283            TokenState::NoTokensLeft {
4284                max_token_count,
4285                token_count,
4286            } => (Color::Error, token_count, max_token_count),
4287            TokenState::HasMoreTokens {
4288                max_token_count,
4289                token_count,
4290                over_warn_threshold,
4291            } => {
4292                let color = if over_warn_threshold {
4293                    Color::Warning
4294                } else {
4295                    Color::Muted
4296                };
4297                (color, token_count, max_token_count)
4298            }
4299        };
4300        Some(
4301            h_flex()
4302                .gap_0p5()
4303                .child(
4304                    Label::new(humanize_token_count(token_count))
4305                        .size(LabelSize::Small)
4306                        .color(token_count_color),
4307                )
4308                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
4309                .child(
4310                    Label::new(humanize_token_count(max_token_count))
4311                        .size(LabelSize::Small)
4312                        .color(Color::Muted),
4313                ),
4314        )
4315    }
4316}
4317
4318impl Render for ContextEditorToolbarItem {
4319    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4320        let left_side = h_flex()
4321            .pl_1()
4322            .gap_2()
4323            .flex_1()
4324            .min_w(rems(DEFAULT_TAB_TITLE.len() as f32))
4325            .when(self.active_context_editor.is_some(), |left_side| {
4326                left_side.child(self.model_summary_editor.clone())
4327            });
4328        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
4329        let active_model = LanguageModelRegistry::read_global(cx).active_model();
4330        let weak_self = cx.view().downgrade();
4331        let right_side = h_flex()
4332            .gap_2()
4333            // TODO display this in a nicer way, once we have a design for it.
4334            // .children({
4335            //     let project = self
4336            //         .workspace
4337            //         .upgrade()
4338            //         .map(|workspace| workspace.read(cx).project().downgrade());
4339            //
4340            //     let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
4341            //         project.and_then(|project| db.remaining_summaries(&project, cx))
4342            //     });
4343
4344            //     scan_items_remaining
4345            //         .map(|remaining_items| format!("Files to scan: {}", remaining_items))
4346            // })
4347            .child(
4348                ModelSelector::new(
4349                    self.fs.clone(),
4350                    ButtonLike::new("active-model")
4351                        .style(ButtonStyle::Subtle)
4352                        .child(
4353                            h_flex()
4354                                .w_full()
4355                                .gap_0p5()
4356                                .child(
4357                                    div()
4358                                        .overflow_x_hidden()
4359                                        .flex_grow()
4360                                        .whitespace_nowrap()
4361                                        .child(match (active_provider, active_model) {
4362                                            (Some(provider), Some(model)) => h_flex()
4363                                                .gap_1()
4364                                                .child(
4365                                                    Icon::new(model.icon().unwrap_or_else(|| provider.icon()))
4366                                                        .color(Color::Muted)
4367                                                        .size(IconSize::XSmall),
4368                                                )
4369                                                .child(
4370                                                    Label::new(model.name().0)
4371                                                        .size(LabelSize::Small)
4372                                                        .color(Color::Muted),
4373                                                )
4374                                                .into_any_element(),
4375                                            _ => Label::new("No model selected")
4376                                                .size(LabelSize::Small)
4377                                                .color(Color::Muted)
4378                                                .into_any_element(),
4379                                        }),
4380                                )
4381                                .child(
4382                                    Icon::new(IconName::ChevronDown)
4383                                        .color(Color::Muted)
4384                                        .size(IconSize::XSmall),
4385                                ),
4386                        )
4387                        .tooltip(move |cx| {
4388                            Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
4389                        }),
4390                )
4391                .with_handle(self.model_selector_menu_handle.clone()),
4392            )
4393            .children(self.render_remaining_tokens(cx))
4394            .child(
4395                PopoverMenu::new("context-editor-popover")
4396                    .trigger(
4397                        IconButton::new("context-editor-trigger", IconName::EllipsisVertical)
4398                            .icon_size(IconSize::Small)
4399                            .tooltip(|cx| Tooltip::text("Open Context Options", cx)),
4400                    )
4401                    .menu({
4402                        let weak_self = weak_self.clone();
4403                        move |cx| {
4404                            let weak_self = weak_self.clone();
4405                            Some(ContextMenu::build(cx, move |menu, cx| {
4406                                let context = weak_self
4407                                    .update(cx, |this, cx| {
4408                                        active_editor_focus_handle(&this.workspace, cx)
4409                                    })
4410                                    .ok()
4411                                    .flatten();
4412                                menu.when_some(context, |menu, context| menu.context(context))
4413                                    .entry("Regenerate Context Title", None, {
4414                                        let weak_self = weak_self.clone();
4415                                        move |cx| {
4416                                            weak_self
4417                                                .update(cx, |_, cx| {
4418                                                    cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
4419                                                })
4420                                                .ok();
4421                                        }
4422                                    })
4423                                    .custom_entry(
4424                                        |_| {
4425                                            h_flex()
4426                                                .w_full()
4427                                                .justify_between()
4428                                                .gap_2()
4429                                                .child(Label::new("Insert Context"))
4430                                                .child(Label::new("/ command").color(Color::Muted))
4431                                                .into_any()
4432                                        },
4433                                        {
4434                                            let weak_self = weak_self.clone();
4435                                            move |cx| {
4436                                                weak_self
4437                                                    .update(cx, |this, cx| {
4438                                                        if let Some(editor) =
4439                                                        &this.active_context_editor
4440                                                        {
4441                                                            editor
4442                                                                .update(cx, |this, cx| {
4443                                                                    this.slash_menu_handle
4444                                                                        .toggle(cx);
4445                                                                })
4446                                                                .ok();
4447                                                        }
4448                                                    })
4449                                                    .ok();
4450                                            }
4451                                        },
4452                                    )
4453                                    .action("Insert Selection", QuoteSelection.boxed_clone())
4454                            }))
4455                        }
4456                    }),
4457            );
4458
4459        h_flex()
4460            .size_full()
4461            .gap_2()
4462            .justify_between()
4463            .child(left_side)
4464            .child(right_side)
4465    }
4466}
4467
4468impl ToolbarItemView for ContextEditorToolbarItem {
4469    fn set_active_pane_item(
4470        &mut self,
4471        active_pane_item: Option<&dyn ItemHandle>,
4472        cx: &mut ViewContext<Self>,
4473    ) -> ToolbarItemLocation {
4474        self.active_context_editor = active_pane_item
4475            .and_then(|item| item.act_as::<ContextEditor>(cx))
4476            .map(|editor| editor.downgrade());
4477        cx.notify();
4478        if self.active_context_editor.is_none() {
4479            ToolbarItemLocation::Hidden
4480        } else {
4481            ToolbarItemLocation::PrimaryRight
4482        }
4483    }
4484
4485    fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
4486        cx.notify();
4487    }
4488}
4489
4490impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
4491
4492enum ContextEditorToolbarItemEvent {
4493    RegenerateSummary,
4494}
4495impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
4496
4497pub struct ContextHistory {
4498    picker: View<Picker<SavedContextPickerDelegate>>,
4499    _subscriptions: Vec<Subscription>,
4500    assistant_panel: WeakView<AssistantPanel>,
4501}
4502
4503impl ContextHistory {
4504    fn new(
4505        project: Model<Project>,
4506        context_store: Model<ContextStore>,
4507        assistant_panel: WeakView<AssistantPanel>,
4508        cx: &mut ViewContext<Self>,
4509    ) -> Self {
4510        let picker = cx.new_view(|cx| {
4511            Picker::uniform_list(
4512                SavedContextPickerDelegate::new(project, context_store.clone()),
4513                cx,
4514            )
4515            .modal(false)
4516            .max_height(None)
4517        });
4518
4519        let _subscriptions = vec![
4520            cx.observe(&context_store, |this, _, cx| {
4521                this.picker.update(cx, |picker, cx| picker.refresh(cx));
4522            }),
4523            cx.subscribe(&picker, Self::handle_picker_event),
4524        ];
4525
4526        Self {
4527            picker,
4528            _subscriptions,
4529            assistant_panel,
4530        }
4531    }
4532
4533    fn handle_picker_event(
4534        &mut self,
4535        _: View<Picker<SavedContextPickerDelegate>>,
4536        event: &SavedContextPickerEvent,
4537        cx: &mut ViewContext<Self>,
4538    ) {
4539        let SavedContextPickerEvent::Confirmed(context) = event;
4540        self.assistant_panel
4541            .update(cx, |assistant_panel, cx| match context {
4542                ContextMetadata::Remote(metadata) => {
4543                    assistant_panel
4544                        .open_remote_context(metadata.id.clone(), cx)
4545                        .detach_and_log_err(cx);
4546                }
4547                ContextMetadata::Saved(metadata) => {
4548                    assistant_panel
4549                        .open_saved_context(metadata.path.clone(), cx)
4550                        .detach_and_log_err(cx);
4551                }
4552            })
4553            .ok();
4554    }
4555}
4556
4557#[derive(Debug, PartialEq, Eq, Clone, Copy)]
4558pub enum WorkflowAssistStatus {
4559    Pending,
4560    Confirmed,
4561    Done,
4562    Idle,
4563}
4564
4565impl Render for ContextHistory {
4566    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
4567        div().size_full().child(self.picker.clone())
4568    }
4569}
4570
4571impl FocusableView for ContextHistory {
4572    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4573        self.picker.focus_handle(cx)
4574    }
4575}
4576
4577impl EventEmitter<()> for ContextHistory {}
4578
4579impl Item for ContextHistory {
4580    type Event = ();
4581
4582    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4583        Some("History".into())
4584    }
4585}
4586
4587pub struct ConfigurationView {
4588    focus_handle: FocusHandle,
4589    configuration_views: HashMap<LanguageModelProviderId, AnyView>,
4590    _registry_subscription: Subscription,
4591}
4592
4593impl ConfigurationView {
4594    fn new(cx: &mut ViewContext<Self>) -> Self {
4595        let focus_handle = cx.focus_handle();
4596
4597        let registry_subscription = cx.subscribe(
4598            &LanguageModelRegistry::global(cx),
4599            |this, _, event: &language_model::Event, cx| match event {
4600                language_model::Event::AddedProvider(provider_id) => {
4601                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
4602                    if let Some(provider) = provider {
4603                        this.add_configuration_view(&provider, cx);
4604                    }
4605                }
4606                language_model::Event::RemovedProvider(provider_id) => {
4607                    this.remove_configuration_view(provider_id);
4608                }
4609                _ => {}
4610            },
4611        );
4612
4613        let mut this = Self {
4614            focus_handle,
4615            configuration_views: HashMap::default(),
4616            _registry_subscription: registry_subscription,
4617        };
4618        this.build_configuration_views(cx);
4619        this
4620    }
4621
4622    fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
4623        let providers = LanguageModelRegistry::read_global(cx).providers();
4624        for provider in providers {
4625            self.add_configuration_view(&provider, cx);
4626        }
4627    }
4628
4629    fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
4630        self.configuration_views.remove(provider_id);
4631    }
4632
4633    fn add_configuration_view(
4634        &mut self,
4635        provider: &Arc<dyn LanguageModelProvider>,
4636        cx: &mut ViewContext<Self>,
4637    ) {
4638        let configuration_view = provider.configuration_view(cx);
4639        self.configuration_views
4640            .insert(provider.id(), configuration_view);
4641    }
4642
4643    fn render_provider_view(
4644        &mut self,
4645        provider: &Arc<dyn LanguageModelProvider>,
4646        cx: &mut ViewContext<Self>,
4647    ) -> Div {
4648        let provider_id = provider.id().0.clone();
4649        let provider_name = provider.name().0.clone();
4650        let configuration_view = self.configuration_views.get(&provider.id()).cloned();
4651
4652        let open_new_context = cx.listener({
4653            let provider = provider.clone();
4654            move |_, _, cx| {
4655                cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
4656                    provider.clone(),
4657                ))
4658            }
4659        });
4660
4661        v_flex()
4662            .gap_2()
4663            .child(
4664                h_flex()
4665                    .justify_between()
4666                    .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
4667                    .when(provider.is_authenticated(cx), move |this| {
4668                        this.child(
4669                            h_flex().justify_end().child(
4670                                Button::new(
4671                                    SharedString::from(format!("new-context-{provider_id}")),
4672                                    "Open new context",
4673                                )
4674                                .icon_position(IconPosition::Start)
4675                                .icon(IconName::Plus)
4676                                .style(ButtonStyle::Filled)
4677                                .layer(ElevationIndex::ModalSurface)
4678                                .on_click(open_new_context),
4679                            ),
4680                        )
4681                    }),
4682            )
4683            .child(
4684                div()
4685                    .p(Spacing::Large.rems(cx))
4686                    .bg(cx.theme().colors().surface_background)
4687                    .border_1()
4688                    .border_color(cx.theme().colors().border_variant)
4689                    .rounded_md()
4690                    .when(configuration_view.is_none(), |this| {
4691                        this.child(div().child(Label::new(format!(
4692                            "No configuration view for {}",
4693                            provider_name
4694                        ))))
4695                    })
4696                    .when_some(configuration_view, |this, configuration_view| {
4697                        this.child(configuration_view)
4698                    }),
4699            )
4700    }
4701}
4702
4703impl Render for ConfigurationView {
4704    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4705        let providers = LanguageModelRegistry::read_global(cx).providers();
4706        let provider_views = providers
4707            .into_iter()
4708            .map(|provider| self.render_provider_view(&provider, cx))
4709            .collect::<Vec<_>>();
4710
4711        let mut element = v_flex()
4712            .id("assistant-configuration-view")
4713            .track_focus(&self.focus_handle)
4714            .bg(cx.theme().colors().editor_background)
4715            .size_full()
4716            .overflow_y_scroll()
4717            .child(
4718                v_flex()
4719                    .p(Spacing::XXLarge.rems(cx))
4720                    .border_b_1()
4721                    .border_color(cx.theme().colors().border)
4722                    .gap_1()
4723                    .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
4724                    .child(
4725                        Label::new(
4726                            "At least one LLM provider must be configured to use the Assistant.",
4727                        )
4728                        .color(Color::Muted),
4729                    ),
4730            )
4731            .child(
4732                v_flex()
4733                    .p(Spacing::XXLarge.rems(cx))
4734                    .mt_1()
4735                    .gap_6()
4736                    .flex_1()
4737                    .children(provider_views),
4738            )
4739            .into_any();
4740
4741        // We use a canvas here to get scrolling to work in the ConfigurationView. It's a workaround
4742        // because we couldn't the element to take up the size of the parent.
4743        canvas(
4744            move |bounds, cx| {
4745                element.prepaint_as_root(bounds.origin, bounds.size.into(), cx);
4746                element
4747            },
4748            |_, mut element, cx| {
4749                element.paint(cx);
4750            },
4751        )
4752        .flex_1()
4753        .w_full()
4754    }
4755}
4756
4757pub enum ConfigurationViewEvent {
4758    NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
4759}
4760
4761impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
4762
4763impl FocusableView for ConfigurationView {
4764    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
4765        self.focus_handle.clone()
4766    }
4767}
4768
4769impl Item for ConfigurationView {
4770    type Event = ConfigurationViewEvent;
4771
4772    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4773        Some("Configuration".into())
4774    }
4775}
4776
4777type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
4778
4779fn render_slash_command_output_toggle(
4780    row: MultiBufferRow,
4781    is_folded: bool,
4782    fold: ToggleFold,
4783    _cx: &mut WindowContext,
4784) -> AnyElement {
4785    Disclosure::new(
4786        ("slash-command-output-fold-indicator", row.0 as u64),
4787        !is_folded,
4788    )
4789    .selected(is_folded)
4790    .on_click(move |_e, cx| fold(!is_folded, cx))
4791    .into_any_element()
4792}
4793
4794fn fold_toggle(
4795    name: &'static str,
4796) -> impl Fn(
4797    MultiBufferRow,
4798    bool,
4799    Arc<dyn Fn(bool, &mut WindowContext<'_>) + Send + Sync>,
4800    &mut WindowContext<'_>,
4801) -> AnyElement {
4802    move |row, is_folded, fold, _cx| {
4803        Disclosure::new((name, row.0 as u64), !is_folded)
4804            .selected(is_folded)
4805            .on_click(move |_e, cx| fold(!is_folded, cx))
4806            .into_any_element()
4807    }
4808}
4809
4810fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) -> FoldPlaceholder {
4811    FoldPlaceholder {
4812        render: Arc::new({
4813            move |fold_id, fold_range, _cx| {
4814                let editor = editor.clone();
4815                ButtonLike::new(fold_id)
4816                    .style(ButtonStyle::Filled)
4817                    .layer(ElevationIndex::ElevatedSurface)
4818                    .child(Icon::new(IconName::TextSnippet))
4819                    .child(Label::new(title.clone()).single_line())
4820                    .on_click(move |_, cx| {
4821                        editor
4822                            .update(cx, |editor, cx| {
4823                                let buffer_start = fold_range
4824                                    .start
4825                                    .to_point(&editor.buffer().read(cx).read(cx));
4826                                let buffer_row = MultiBufferRow(buffer_start.row);
4827                                editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4828                            })
4829                            .ok();
4830                    })
4831                    .into_any_element()
4832            }
4833        }),
4834        constrain_width: false,
4835        merge_adjacent: false,
4836    }
4837}
4838
4839fn render_quote_selection_output_toggle(
4840    row: MultiBufferRow,
4841    is_folded: bool,
4842    fold: ToggleFold,
4843    _cx: &mut WindowContext,
4844) -> AnyElement {
4845    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
4846        .selected(is_folded)
4847        .on_click(move |_e, cx| fold(!is_folded, cx))
4848        .into_any_element()
4849}
4850
4851fn render_pending_slash_command_gutter_decoration(
4852    row: MultiBufferRow,
4853    status: &PendingSlashCommandStatus,
4854    confirm_command: Arc<dyn Fn(&mut WindowContext)>,
4855) -> AnyElement {
4856    let mut icon = IconButton::new(
4857        ("slash-command-gutter-decoration", row.0),
4858        ui::IconName::TriangleRight,
4859    )
4860    .on_click(move |_e, cx| confirm_command(cx))
4861    .icon_size(ui::IconSize::Small)
4862    .size(ui::ButtonSize::None);
4863
4864    match status {
4865        PendingSlashCommandStatus::Idle => {
4866            icon = icon.icon_color(Color::Muted);
4867        }
4868        PendingSlashCommandStatus::Running { .. } => {
4869            icon = icon.selected(true);
4870        }
4871        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
4872    }
4873
4874    icon.into_any_element()
4875}
4876
4877fn render_docs_slash_command_trailer(
4878    row: MultiBufferRow,
4879    command: PendingSlashCommand,
4880    cx: &mut WindowContext,
4881) -> AnyElement {
4882    if command.arguments.is_empty() {
4883        return Empty.into_any();
4884    }
4885    let args = DocsSlashCommandArgs::parse(&command.arguments);
4886
4887    let Some(store) = args
4888        .provider()
4889        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
4890    else {
4891        return Empty.into_any();
4892    };
4893
4894    let Some(package) = args.package() else {
4895        return Empty.into_any();
4896    };
4897
4898    let mut children = Vec::new();
4899
4900    if store.is_indexing(&package) {
4901        children.push(
4902            div()
4903                .id(("crates-being-indexed", row.0))
4904                .child(Icon::new(IconName::ArrowCircle).with_animation(
4905                    "arrow-circle",
4906                    Animation::new(Duration::from_secs(4)).repeat(),
4907                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
4908                ))
4909                .tooltip({
4910                    let package = package.clone();
4911                    move |cx| Tooltip::text(format!("Indexing {package}"), cx)
4912                })
4913                .into_any_element(),
4914        );
4915    }
4916
4917    if let Some(latest_error) = store.latest_error_for_package(&package) {
4918        children.push(
4919            div()
4920                .id(("latest-error", row.0))
4921                .child(
4922                    Icon::new(IconName::Warning)
4923                        .size(IconSize::Small)
4924                        .color(Color::Warning),
4925                )
4926                .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
4927                .into_any_element(),
4928        )
4929    }
4930
4931    let is_indexing = store.is_indexing(&package);
4932    let latest_error = store.latest_error_for_package(&package);
4933
4934    if !is_indexing && latest_error.is_none() {
4935        return Empty.into_any();
4936    }
4937
4938    h_flex().gap_2().children(children).into_any_element()
4939}
4940
4941fn make_lsp_adapter_delegate(
4942    project: &Model<Project>,
4943    cx: &mut AppContext,
4944) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
4945    project.update(cx, |project, cx| {
4946        // TODO: Find the right worktree.
4947        let Some(worktree) = project.worktrees(cx).next() else {
4948            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
4949        };
4950        let http_client = project.client().http_client().clone();
4951        project.lsp_store().update(cx, |lsp_store, cx| {
4952            Ok(Some(LocalLspAdapterDelegate::new(
4953                lsp_store,
4954                &worktree,
4955                http_client,
4956                project.fs().clone(),
4957                cx,
4958            ) as Arc<dyn LspAdapterDelegate>))
4959        })
4960    })
4961}
4962
4963fn slash_command_error_block_renderer(message: String) -> RenderBlock {
4964    Box::new(move |_| {
4965        div()
4966            .pl_6()
4967            .child(
4968                Label::new(format!("error: {}", message))
4969                    .single_line()
4970                    .color(Color::Error),
4971            )
4972            .into_any()
4973    })
4974}
4975
4976enum TokenState {
4977    NoTokensLeft {
4978        max_token_count: usize,
4979        token_count: usize,
4980    },
4981    HasMoreTokens {
4982        max_token_count: usize,
4983        token_count: usize,
4984        over_warn_threshold: bool,
4985    },
4986}
4987
4988fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
4989    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
4990
4991    let model = LanguageModelRegistry::read_global(cx).active_model()?;
4992    let token_count = context.read(cx).token_count()?;
4993    let max_token_count = model.max_token_count();
4994
4995    let remaining_tokens = max_token_count as isize - token_count as isize;
4996    let token_state = if remaining_tokens <= 0 {
4997        TokenState::NoTokensLeft {
4998            max_token_count,
4999            token_count,
5000        }
5001    } else {
5002        let over_warn_threshold =
5003            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
5004        TokenState::HasMoreTokens {
5005            max_token_count,
5006            token_count,
5007            over_warn_threshold,
5008        }
5009    };
5010    Some(token_state)
5011}
5012
5013fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
5014    let image_size = data
5015        .size(0)
5016        .map(|dimension| Pixels::from(u32::from(dimension)));
5017    let image_ratio = image_size.width / image_size.height;
5018    let bounds_ratio = max_size.width / max_size.height;
5019
5020    if image_size.width > max_size.width || image_size.height > max_size.height {
5021        if bounds_ratio > image_ratio {
5022            size(
5023                image_size.width * (max_size.height / image_size.height),
5024                max_size.height,
5025            )
5026        } else {
5027            size(
5028                max_size.width,
5029                image_size.height * (max_size.width / image_size.width),
5030            )
5031        }
5032    } else {
5033        size(image_size.width, image_size.height)
5034    }
5035}
5036
5037enum ConfigurationError {
5038    NoProvider,
5039    ProviderNotAuthenticated,
5040}
5041
5042fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
5043    let provider = LanguageModelRegistry::read_global(cx).active_provider();
5044    let is_authenticated = provider
5045        .as_ref()
5046        .map_or(false, |provider| provider.is_authenticated(cx));
5047
5048    if provider.is_some() && is_authenticated {
5049        return None;
5050    }
5051
5052    if provider.is_none() {
5053        return Some(ConfigurationError::NoProvider);
5054    }
5055
5056    if !is_authenticated {
5057        return Some(ConfigurationError::ProviderNotAuthenticated);
5058    }
5059
5060    None
5061}
5062
5063#[cfg(test)]
5064mod tests {
5065    use super::*;
5066    use gpui::{AppContext, Context};
5067    use language::Buffer;
5068    use unindent::Unindent;
5069
5070    #[gpui::test]
5071    fn test_find_code_blocks(cx: &mut AppContext) {
5072        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
5073
5074        let buffer = cx.new_model(|cx| {
5075            let text = r#"
5076                line 0
5077                line 1
5078                ```rust
5079                fn main() {}
5080                ```
5081                line 5
5082                line 6
5083                line 7
5084                ```go
5085                func main() {}
5086                ```
5087                line 11
5088                ```
5089                this is plain text code block
5090                ```
5091
5092                ```go
5093                func another() {}
5094                ```
5095                line 19
5096            "#
5097            .unindent();
5098            let mut buffer = Buffer::local(text, cx);
5099            buffer.set_language(Some(markdown.clone()), cx);
5100            buffer
5101        });
5102        let snapshot = buffer.read(cx).snapshot();
5103
5104        let code_blocks = vec![
5105            Point::new(3, 0)..Point::new(4, 0),
5106            Point::new(9, 0)..Point::new(10, 0),
5107            Point::new(13, 0)..Point::new(14, 0),
5108            Point::new(17, 0)..Point::new(18, 0),
5109        ]
5110        .into_iter()
5111        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
5112        .collect::<Vec<_>>();
5113
5114        let expected_results = vec![
5115            (0, None),
5116            (1, None),
5117            (2, Some(code_blocks[0].clone())),
5118            (3, Some(code_blocks[0].clone())),
5119            (4, Some(code_blocks[0].clone())),
5120            (5, None),
5121            (6, None),
5122            (7, None),
5123            (8, Some(code_blocks[1].clone())),
5124            (9, Some(code_blocks[1].clone())),
5125            (10, Some(code_blocks[1].clone())),
5126            (11, None),
5127            (12, Some(code_blocks[2].clone())),
5128            (13, Some(code_blocks[2].clone())),
5129            (14, Some(code_blocks[2].clone())),
5130            (15, None),
5131            (16, Some(code_blocks[3].clone())),
5132            (17, Some(code_blocks[3].clone())),
5133            (18, Some(code_blocks[3].clone())),
5134            (19, None),
5135        ];
5136
5137        for (row, expected) in expected_results {
5138            let offset = snapshot.point_to_offset(Point::new(row, 0));
5139            let range = find_surrounding_code_block(&snapshot, offset);
5140            assert_eq!(range, expected, "unexpected result on row {:?}", row);
5141        }
5142    }
5143}