assistant_panel.rs

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