assistant_panel.rs

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