assistant_panel.rs

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