assistant_panel.rs

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