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