assistant_panel.rs

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