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