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        SlashCommandCompletionProvider, SlashCommandRegistry,
  10    },
  11    terminal_inline_assistant::TerminalInlineAssistant,
  12    Assist, CodegenStatus, ConfirmCommand, Context, ContextEvent, ContextId, ContextStore,
  13    CycleMessageRole, DebugEditSteps, DeployHistory, DeployPromptLibrary, InlineAssist,
  14    InlineAssistId, InlineAssistant, InsertIntoEditor, MessageStatus, ModelSelector,
  15    PendingSlashCommand, PendingSlashCommandStatus, QuoteSelection, RemoteContextMetadata,
  16    ResolvedWorkflowStep, SavedContextMetadata, Split, ToggleFocus, ToggleModelSelector,
  17    WorkflowStepStatus,
  18};
  19use crate::{ContextStoreEvent, ShowConfiguration};
  20use anyhow::{anyhow, Context as _, Result};
  21use assistant_slash_command::{SlashCommand, SlashCommandOutputSection};
  22use client::{proto, Client, Status};
  23use collections::{BTreeSet, HashMap, HashSet};
  24use editor::{
  25    actions::{FoldAt, MoveToEndOfLine, Newline, ShowCompletions, UnfoldAt},
  26    display_map::{
  27        BlockDisposition, BlockProperties, BlockStyle, Crease, CustomBlockId, RenderBlock,
  28        ToDisplayPoint,
  29    },
  30    scroll::{Autoscroll, AutoscrollStrategy, ScrollAnchor},
  31    Anchor, Editor, EditorEvent, ExcerptRange, MultiBuffer, RowExt, ToOffset as _, ToPoint,
  32};
  33use editor::{display_map::CreaseId, FoldPlaceholder};
  34use fs::Fs;
  35use gpui::{
  36    div, percentage, point, Action, Animation, AnimationExt, AnyElement, AnyView, AppContext,
  37    AsyncWindowContext, ClipboardItem, Context as _, DismissEvent, Empty, Entity, EventEmitter,
  38    FocusHandle, FocusableView, FontWeight, InteractiveElement, IntoElement, Model, ParentElement,
  39    Pixels, ReadGlobal, Render, SharedString, StatefulInteractiveElement, Styled, Subscription,
  40    Task, Transformation, UpdateGlobal, View, ViewContext, VisualContext, WeakView, WindowContext,
  41};
  42use indexed_docs::IndexedDocsStore;
  43use language::{
  44    language_settings::SoftWrap, Capability, LanguageRegistry, LspAdapterDelegate, Point, ToOffset,
  45};
  46use language_model::{
  47    provider::cloud::PROVIDER_ID, LanguageModelProvider, LanguageModelProviderId,
  48    LanguageModelRegistry, Role,
  49};
  50use multi_buffer::MultiBufferRow;
  51use picker::{Picker, PickerDelegate};
  52use project::{Project, ProjectLspAdapterDelegate};
  53use search::{buffer_search::DivRegistrar, BufferSearchBar};
  54use settings::{update_settings_file, Settings};
  55use smol::stream::StreamExt;
  56use std::{
  57    borrow::Cow,
  58    cmp::{self, Ordering},
  59    fmt::Write,
  60    ops::Range,
  61    path::PathBuf,
  62    sync::Arc,
  63    time::Duration,
  64};
  65use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
  66use ui::TintColor;
  67use ui::{
  68    prelude::*,
  69    utils::{format_distance_from_now, DateTimeType},
  70    Avatar, AvatarShape, ButtonLike, ContextMenu, Disclosure, ElevationIndex, KeyBinding, ListItem,
  71    ListItemSpacing, PopoverMenu, PopoverMenuHandle, Tooltip,
  72};
  73use util::ResultExt;
  74use workspace::{
  75    dock::{DockPosition, Panel, PanelEvent},
  76    item::{self, FollowableItem, Item, ItemHandle},
  77    notifications::NotifyTaskExt,
  78    pane::{self, SaveIntent},
  79    searchable::{SearchEvent, SearchableItem},
  80    Pane, Save, ToggleZoom, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
  81};
  82use workspace::{searchable::SearchableItemHandle, NewFile};
  83
  84pub fn init(cx: &mut AppContext) {
  85    workspace::FollowableViewRegistry::register::<ContextEditor>(cx);
  86    cx.observe_new_views(
  87        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  88            workspace
  89                .register_action(|workspace, _: &ToggleFocus, cx| {
  90                    let settings = AssistantSettings::get_global(cx);
  91                    if !settings.enabled {
  92                        return;
  93                    }
  94
  95                    workspace.toggle_panel_focus::<AssistantPanel>(cx);
  96                })
  97                .register_action(AssistantPanel::inline_assist)
  98                .register_action(ContextEditor::quote_selection)
  99                .register_action(ContextEditor::insert_selection)
 100                .register_action(AssistantPanel::show_configuration);
 101        },
 102    )
 103    .detach();
 104
 105    cx.observe_new_views(
 106        |terminal_panel: &mut TerminalPanel, cx: &mut ViewContext<TerminalPanel>| {
 107            let settings = AssistantSettings::get_global(cx);
 108            if !settings.enabled {
 109                return;
 110            }
 111
 112            terminal_panel.register_tab_bar_button(cx.new_view(|_| InlineAssistTabBarButton), cx);
 113        },
 114    )
 115    .detach();
 116}
 117
 118struct InlineAssistTabBarButton;
 119
 120impl Render for InlineAssistTabBarButton {
 121    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 122        IconButton::new("terminal_inline_assistant", IconName::MagicWand)
 123            .icon_size(IconSize::Small)
 124            .on_click(cx.listener(|_, _, cx| {
 125                cx.dispatch_action(InlineAssist::default().boxed_clone());
 126            }))
 127            .tooltip(move |cx| Tooltip::for_action("Inline Assist", &InlineAssist::default(), cx))
 128    }
 129}
 130
 131pub enum AssistantPanelEvent {
 132    ContextEdited,
 133}
 134
 135pub struct AssistantPanel {
 136    pane: View<Pane>,
 137    workspace: WeakView<Workspace>,
 138    width: Option<Pixels>,
 139    height: Option<Pixels>,
 140    project: Model<Project>,
 141    context_store: Model<ContextStore>,
 142    languages: Arc<LanguageRegistry>,
 143    fs: Arc<dyn Fs>,
 144    subscriptions: Vec<Subscription>,
 145    model_selector_menu_handle: PopoverMenuHandle<ContextMenu>,
 146    model_summary_editor: View<Editor>,
 147    authenticate_provider_task: Option<(LanguageModelProviderId, Task<()>)>,
 148    configuration_subscription: Option<Subscription>,
 149    client_status: Option<client::Status>,
 150    watch_client_status: Option<Task<()>>,
 151    show_zed_ai_notice: bool,
 152}
 153
 154#[derive(Clone)]
 155enum ContextMetadata {
 156    Remote(RemoteContextMetadata),
 157    Saved(SavedContextMetadata),
 158}
 159
 160struct SavedContextPickerDelegate {
 161    store: Model<ContextStore>,
 162    project: Model<Project>,
 163    matches: Vec<ContextMetadata>,
 164    selected_index: usize,
 165}
 166
 167enum SavedContextPickerEvent {
 168    Confirmed(ContextMetadata),
 169}
 170
 171enum InlineAssistTarget {
 172    Editor(View<Editor>, bool),
 173    Terminal(View<TerminalView>),
 174}
 175
 176impl EventEmitter<SavedContextPickerEvent> for Picker<SavedContextPickerDelegate> {}
 177
 178impl SavedContextPickerDelegate {
 179    fn new(project: Model<Project>, store: Model<ContextStore>) -> Self {
 180        Self {
 181            project,
 182            store,
 183            matches: Vec::new(),
 184            selected_index: 0,
 185        }
 186    }
 187}
 188
 189impl PickerDelegate for SavedContextPickerDelegate {
 190    type ListItem = ListItem;
 191
 192    fn match_count(&self) -> usize {
 193        self.matches.len()
 194    }
 195
 196    fn selected_index(&self) -> usize {
 197        self.selected_index
 198    }
 199
 200    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
 201        self.selected_index = ix;
 202    }
 203
 204    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
 205        "Search...".into()
 206    }
 207
 208    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
 209        let search = self.store.read(cx).search(query, cx);
 210        cx.spawn(|this, mut cx| async move {
 211            let matches = search.await;
 212            this.update(&mut cx, |this, cx| {
 213                let host_contexts = this.delegate.store.read(cx).host_contexts();
 214                this.delegate.matches = host_contexts
 215                    .iter()
 216                    .cloned()
 217                    .map(ContextMetadata::Remote)
 218                    .chain(matches.into_iter().map(ContextMetadata::Saved))
 219                    .collect();
 220                this.delegate.selected_index = 0;
 221                cx.notify();
 222            })
 223            .ok();
 224        })
 225    }
 226
 227    fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
 228        if let Some(metadata) = self.matches.get(self.selected_index) {
 229            cx.emit(SavedContextPickerEvent::Confirmed(metadata.clone()));
 230        }
 231    }
 232
 233    fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
 234
 235    fn render_match(
 236        &self,
 237        ix: usize,
 238        selected: bool,
 239        cx: &mut ViewContext<Picker<Self>>,
 240    ) -> Option<Self::ListItem> {
 241        let context = self.matches.get(ix)?;
 242        let item = match context {
 243            ContextMetadata::Remote(context) => {
 244                let host_user = self.project.read(cx).host().and_then(|collaborator| {
 245                    self.project
 246                        .read(cx)
 247                        .user_store()
 248                        .read(cx)
 249                        .get_cached_user(collaborator.user_id)
 250                });
 251                div()
 252                    .flex()
 253                    .w_full()
 254                    .justify_between()
 255                    .gap_2()
 256                    .child(
 257                        h_flex().flex_1().overflow_x_hidden().child(
 258                            Label::new(context.summary.clone().unwrap_or(DEFAULT_TAB_TITLE.into()))
 259                                .size(LabelSize::Small),
 260                        ),
 261                    )
 262                    .child(
 263                        h_flex()
 264                            .gap_2()
 265                            .children(if let Some(host_user) = host_user {
 266                                vec![
 267                                    Avatar::new(host_user.avatar_uri.clone())
 268                                        .shape(AvatarShape::Circle)
 269                                        .into_any_element(),
 270                                    Label::new(format!("Shared by @{}", host_user.github_login))
 271                                        .color(Color::Muted)
 272                                        .size(LabelSize::Small)
 273                                        .into_any_element(),
 274                                ]
 275                            } else {
 276                                vec![Label::new("Shared by host")
 277                                    .color(Color::Muted)
 278                                    .size(LabelSize::Small)
 279                                    .into_any_element()]
 280                            }),
 281                    )
 282            }
 283            ContextMetadata::Saved(context) => div()
 284                .flex()
 285                .w_full()
 286                .justify_between()
 287                .gap_2()
 288                .child(
 289                    h_flex()
 290                        .flex_1()
 291                        .child(Label::new(context.title.clone()).size(LabelSize::Small))
 292                        .overflow_x_hidden(),
 293                )
 294                .child(
 295                    Label::new(format_distance_from_now(
 296                        DateTimeType::Local(context.mtime),
 297                        false,
 298                        true,
 299                        true,
 300                    ))
 301                    .color(Color::Muted)
 302                    .size(LabelSize::Small),
 303                ),
 304        };
 305        Some(
 306            ListItem::new(ix)
 307                .inset(true)
 308                .spacing(ListItemSpacing::Sparse)
 309                .selected(selected)
 310                .child(item),
 311        )
 312    }
 313}
 314
 315impl AssistantPanel {
 316    pub fn load(
 317        workspace: WeakView<Workspace>,
 318        prompt_builder: Arc<PromptBuilder>,
 319        cx: AsyncWindowContext,
 320    ) -> Task<Result<View<Self>>> {
 321        cx.spawn(|mut cx| async move {
 322            let context_store = workspace
 323                .update(&mut cx, |workspace, cx| {
 324                    let project = workspace.project().clone();
 325                    ContextStore::new(project, prompt_builder.clone(), cx)
 326                })?
 327                .await?;
 328
 329            workspace.update(&mut cx, |workspace, cx| {
 330                // TODO: deserialize state.
 331                cx.new_view(|cx| Self::new(workspace, context_store, cx))
 332            })
 333        })
 334    }
 335
 336    fn new(
 337        workspace: &Workspace,
 338        context_store: Model<ContextStore>,
 339        cx: &mut ViewContext<Self>,
 340    ) -> Self {
 341        let model_selector_menu_handle = PopoverMenuHandle::default();
 342        let model_summary_editor = cx.new_view(|cx| Editor::single_line(cx));
 343        let context_editor_toolbar = cx.new_view(|_| {
 344            ContextEditorToolbarItem::new(
 345                workspace,
 346                model_selector_menu_handle.clone(),
 347                model_summary_editor.clone(),
 348            )
 349        });
 350        let pane = cx.new_view(|cx| {
 351            let mut pane = Pane::new(
 352                workspace.weak_handle(),
 353                workspace.project().clone(),
 354                Default::default(),
 355                None,
 356                NewFile.boxed_clone(),
 357                cx,
 358            );
 359            pane.set_can_split(false, cx);
 360            pane.set_can_navigate(true, cx);
 361            pane.display_nav_history_buttons(None);
 362            pane.set_should_display_tab_bar(|_| true);
 363            pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
 364                let focus_handle = pane.focus_handle(cx);
 365                let left_children = IconButton::new("history", IconName::TextSearch)
 366                    .on_click(cx.listener({
 367                        let focus_handle = focus_handle.clone();
 368                        move |_, _, cx| {
 369                            focus_handle.focus(cx);
 370                            cx.dispatch_action(DeployHistory.boxed_clone())
 371                        }
 372                    }))
 373                    .tooltip(move |cx| {
 374                        cx.new_view(|cx| {
 375                            let keybind =
 376                                KeyBinding::for_action_in(&DeployHistory, &focus_handle, cx);
 377                            Tooltip::new("History").key_binding(keybind)
 378                        })
 379                        .into()
 380                    })
 381                    .selected(
 382                        pane.active_item()
 383                            .map_or(false, |item| item.downcast::<ContextHistory>().is_some()),
 384                    );
 385                let right_children = h_flex()
 386                    .gap(Spacing::Small.rems(cx))
 387                    .child(
 388                        IconButton::new("new-context", IconName::Plus)
 389                            .on_click(
 390                                cx.listener(|_, _, cx| cx.dispatch_action(NewFile.boxed_clone())),
 391                            )
 392                            .tooltip(|cx| Tooltip::for_action("New Context", &NewFile, cx)),
 393                    )
 394                    .child(
 395                        IconButton::new("menu", IconName::Menu)
 396                            .icon_size(IconSize::Small)
 397                            .on_click(cx.listener(|pane, _, cx| {
 398                                let zoom_label = if pane.is_zoomed() {
 399                                    "Zoom Out"
 400                                } else {
 401                                    "Zoom In"
 402                                };
 403                                let menu = ContextMenu::build(cx, |menu, cx| {
 404                                    menu.context(pane.focus_handle(cx))
 405                                        .action("New Context", Box::new(NewFile))
 406                                        .action("History", Box::new(DeployHistory))
 407                                        .action("Prompt Library", Box::new(DeployPromptLibrary))
 408                                        .action("Configure", Box::new(ShowConfiguration))
 409                                        .action(zoom_label, Box::new(ToggleZoom))
 410                                });
 411                                cx.subscribe(&menu, |pane, _, _: &DismissEvent, _| {
 412                                    pane.new_item_menu = None;
 413                                })
 414                                .detach();
 415                                pane.new_item_menu = Some(menu);
 416                            })),
 417                    )
 418                    .when_some(pane.new_item_menu.as_ref(), |el, new_item_menu| {
 419                        el.child(Pane::render_menu_overlay(new_item_menu))
 420                    })
 421                    .into_any_element()
 422                    .into();
 423
 424                (Some(left_children.into_any_element()), right_children)
 425            });
 426            pane.toolbar().update(cx, |toolbar, cx| {
 427                toolbar.add_item(context_editor_toolbar.clone(), cx);
 428                toolbar.add_item(cx.new_view(BufferSearchBar::new), cx)
 429            });
 430            pane
 431        });
 432
 433        let subscriptions = vec![
 434            cx.observe(&pane, |_, _, cx| cx.notify()),
 435            cx.subscribe(&pane, Self::handle_pane_event),
 436            cx.subscribe(&context_editor_toolbar, Self::handle_toolbar_event),
 437            cx.subscribe(&model_summary_editor, Self::handle_summary_editor_event),
 438            cx.subscribe(&context_store, Self::handle_context_store_event),
 439            cx.subscribe(
 440                &LanguageModelRegistry::global(cx),
 441                |this, _, event: &language_model::Event, cx| match event {
 442                    language_model::Event::ActiveModelChanged => {
 443                        this.completion_provider_changed(cx);
 444                    }
 445                    language_model::Event::ProviderStateChanged => {
 446                        this.ensure_authenticated(cx);
 447                    }
 448                    language_model::Event::AddedProvider(_)
 449                    | language_model::Event::RemovedProvider(_) => {
 450                        this.ensure_authenticated(cx);
 451                    }
 452                },
 453            ),
 454        ];
 455
 456        let watch_client_status = Self::watch_client_status(workspace.client().clone(), cx);
 457
 458        let mut this = Self {
 459            pane,
 460            workspace: workspace.weak_handle(),
 461            width: None,
 462            height: None,
 463            project: workspace.project().clone(),
 464            context_store,
 465            languages: workspace.app_state().languages.clone(),
 466            fs: workspace.app_state().fs.clone(),
 467            subscriptions,
 468            model_selector_menu_handle,
 469            model_summary_editor,
 470            authenticate_provider_task: None,
 471            configuration_subscription: None,
 472            client_status: None,
 473            watch_client_status: Some(watch_client_status),
 474            show_zed_ai_notice: false,
 475        };
 476        this.new_context(cx);
 477        this
 478    }
 479
 480    fn watch_client_status(client: Arc<Client>, cx: &mut ViewContext<Self>) -> Task<()> {
 481        let mut status_rx = client.status();
 482
 483        cx.spawn(|this, mut cx| async move {
 484            while let Some(status) = status_rx.next().await {
 485                this.update(&mut cx, |this, cx| {
 486                    if this.client_status.is_none()
 487                        || this
 488                            .client_status
 489                            .map_or(false, |old_status| old_status != status)
 490                    {
 491                        this.update_zed_ai_notice_visibility(status, cx);
 492                    }
 493                    this.client_status = Some(status);
 494                })
 495                .log_err();
 496            }
 497            this.update(&mut cx, |this, _cx| this.watch_client_status = None)
 498                .log_err();
 499        })
 500    }
 501
 502    fn handle_pane_event(
 503        &mut self,
 504        pane: View<Pane>,
 505        event: &pane::Event,
 506        cx: &mut ViewContext<Self>,
 507    ) {
 508        let update_model_summary = match event {
 509            pane::Event::Remove => {
 510                cx.emit(PanelEvent::Close);
 511                false
 512            }
 513            pane::Event::ZoomIn => {
 514                cx.emit(PanelEvent::ZoomIn);
 515                false
 516            }
 517            pane::Event::ZoomOut => {
 518                cx.emit(PanelEvent::ZoomOut);
 519                false
 520            }
 521
 522            pane::Event::AddItem { item } => {
 523                self.workspace
 524                    .update(cx, |workspace, cx| {
 525                        item.added_to_pane(workspace, self.pane.clone(), cx)
 526                    })
 527                    .ok();
 528                true
 529            }
 530
 531            pane::Event::ActivateItem { local } => {
 532                if *local {
 533                    self.workspace
 534                        .update(cx, |workspace, cx| {
 535                            workspace.unfollow_in_pane(&pane, cx);
 536                        })
 537                        .ok();
 538                }
 539                cx.emit(AssistantPanelEvent::ContextEdited);
 540                true
 541            }
 542
 543            pane::Event::RemoveItem { idx } => {
 544                if self
 545                    .pane
 546                    .read(cx)
 547                    .item_for_index(*idx)
 548                    .map_or(false, |item| item.downcast::<ConfigurationView>().is_some())
 549                {
 550                    self.configuration_subscription = None;
 551                }
 552                false
 553            }
 554            pane::Event::RemovedItem { .. } => {
 555                cx.emit(AssistantPanelEvent::ContextEdited);
 556                true
 557            }
 558
 559            _ => false,
 560        };
 561
 562        if update_model_summary {
 563            if let Some(editor) = self.active_context_editor(cx) {
 564                self.show_updated_summary(&editor, cx)
 565            }
 566        }
 567    }
 568
 569    fn handle_summary_editor_event(
 570        &mut self,
 571        model_summary_editor: View<Editor>,
 572        event: &EditorEvent,
 573        cx: &mut ViewContext<Self>,
 574    ) {
 575        if matches!(event, EditorEvent::Edited { .. }) {
 576            if let Some(context_editor) = self.active_context_editor(cx) {
 577                let new_summary = model_summary_editor.read(cx).text(cx);
 578                context_editor.update(cx, |context_editor, cx| {
 579                    context_editor.context.update(cx, |context, cx| {
 580                        if context.summary().is_none()
 581                            && (new_summary == DEFAULT_TAB_TITLE || new_summary.trim().is_empty())
 582                        {
 583                            return;
 584                        }
 585                        context.custom_summary(new_summary, cx)
 586                    });
 587                });
 588            }
 589        }
 590    }
 591
 592    fn update_zed_ai_notice_visibility(
 593        &mut self,
 594        client_status: Status,
 595        cx: &mut ViewContext<Self>,
 596    ) {
 597        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
 598
 599        // If we're signed out and don't have a provider configured, or we're signed-out AND Zed.dev is
 600        // the provider, we want to show a nudge to sign in.
 601        let show_zed_ai_notice = client_status.is_signed_out()
 602            && active_provider.map_or(true, |provider| provider.id().0 == PROVIDER_ID);
 603
 604        self.show_zed_ai_notice = show_zed_ai_notice;
 605        cx.notify();
 606    }
 607
 608    fn handle_toolbar_event(
 609        &mut self,
 610        _: View<ContextEditorToolbarItem>,
 611        _: &ContextEditorToolbarItemEvent,
 612        cx: &mut ViewContext<Self>,
 613    ) {
 614        if let Some(context_editor) = self.active_context_editor(cx) {
 615            context_editor.update(cx, |context_editor, cx| {
 616                context_editor.context.update(cx, |context, cx| {
 617                    context.summarize(true, cx);
 618                })
 619            })
 620        }
 621    }
 622
 623    fn handle_context_store_event(
 624        &mut self,
 625        _context_store: Model<ContextStore>,
 626        event: &ContextStoreEvent,
 627        cx: &mut ViewContext<Self>,
 628    ) {
 629        let ContextStoreEvent::ContextCreated(context_id) = event;
 630        let Some(context) = self
 631            .context_store
 632            .read(cx)
 633            .loaded_context_for_id(&context_id, cx)
 634        else {
 635            log::error!("no context found with ID: {}", context_id.to_proto());
 636            return;
 637        };
 638        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx).log_err();
 639
 640        let assistant_panel = cx.view().downgrade();
 641        let editor = cx.new_view(|cx| {
 642            let mut editor = ContextEditor::for_context(
 643                context,
 644                self.fs.clone(),
 645                self.workspace.clone(),
 646                self.project.clone(),
 647                lsp_adapter_delegate,
 648                assistant_panel,
 649                cx,
 650            );
 651            editor.insert_default_prompt(cx);
 652            editor
 653        });
 654
 655        self.show_context(editor.clone(), cx);
 656    }
 657
 658    fn completion_provider_changed(&mut self, cx: &mut ViewContext<Self>) {
 659        if let Some(editor) = self.active_context_editor(cx) {
 660            editor.update(cx, |active_context, cx| {
 661                active_context
 662                    .context
 663                    .update(cx, |context, cx| context.completion_provider_changed(cx))
 664            })
 665        }
 666
 667        let Some(new_provider_id) = LanguageModelRegistry::read_global(cx)
 668            .active_provider()
 669            .map(|p| p.id())
 670        else {
 671            return;
 672        };
 673
 674        if self
 675            .authenticate_provider_task
 676            .as_ref()
 677            .map_or(true, |(old_provider_id, _)| {
 678                *old_provider_id != new_provider_id
 679            })
 680        {
 681            self.authenticate_provider_task = None;
 682            self.ensure_authenticated(cx);
 683        }
 684
 685        if let Some(status) = self.client_status {
 686            self.update_zed_ai_notice_visibility(status, cx);
 687        }
 688    }
 689
 690    fn ensure_authenticated(&mut self, cx: &mut ViewContext<Self>) {
 691        if self.is_authenticated(cx) {
 692            return;
 693        }
 694
 695        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
 696            return;
 697        };
 698
 699        let load_credentials = self.authenticate(cx);
 700
 701        if self.authenticate_provider_task.is_none() {
 702            self.authenticate_provider_task = Some((
 703                provider.id(),
 704                cx.spawn(|this, mut cx| async move {
 705                    let _ = load_credentials.await;
 706                    this.update(&mut cx, |this, _cx| {
 707                        this.authenticate_provider_task = None;
 708                    })
 709                    .log_err();
 710                }),
 711            ));
 712        }
 713    }
 714
 715    pub fn inline_assist(
 716        workspace: &mut Workspace,
 717        action: &InlineAssist,
 718        cx: &mut ViewContext<Workspace>,
 719    ) {
 720        let settings = AssistantSettings::get_global(cx);
 721        if !settings.enabled {
 722            return;
 723        }
 724
 725        let Some(assistant_panel) = workspace.panel::<AssistantPanel>(cx) else {
 726            return;
 727        };
 728
 729        let Some(inline_assist_target) =
 730            Self::resolve_inline_assist_target(workspace, &assistant_panel, cx)
 731        else {
 732            return;
 733        };
 734
 735        let initial_prompt = action.prompt.clone();
 736        if assistant_panel.update(cx, |assistant, cx| assistant.is_authenticated(cx)) {
 737            match inline_assist_target {
 738                InlineAssistTarget::Editor(active_editor, include_context) => {
 739                    InlineAssistant::update_global(cx, |assistant, cx| {
 740                        assistant.assist(
 741                            &active_editor,
 742                            Some(cx.view().downgrade()),
 743                            include_context.then_some(&assistant_panel),
 744                            initial_prompt,
 745                            cx,
 746                        )
 747                    })
 748                }
 749                InlineAssistTarget::Terminal(active_terminal) => {
 750                    TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 751                        assistant.assist(
 752                            &active_terminal,
 753                            Some(cx.view().downgrade()),
 754                            Some(&assistant_panel),
 755                            initial_prompt,
 756                            cx,
 757                        )
 758                    })
 759                }
 760            }
 761        } else {
 762            let assistant_panel = assistant_panel.downgrade();
 763            cx.spawn(|workspace, mut cx| async move {
 764                assistant_panel
 765                    .update(&mut cx, |assistant, cx| assistant.authenticate(cx))?
 766                    .await?;
 767                if assistant_panel.update(&mut cx, |panel, cx| panel.is_authenticated(cx))? {
 768                    cx.update(|cx| match inline_assist_target {
 769                        InlineAssistTarget::Editor(active_editor, include_context) => {
 770                            let assistant_panel = if include_context {
 771                                assistant_panel.upgrade()
 772                            } else {
 773                                None
 774                            };
 775                            InlineAssistant::update_global(cx, |assistant, cx| {
 776                                assistant.assist(
 777                                    &active_editor,
 778                                    Some(workspace),
 779                                    assistant_panel.as_ref(),
 780                                    initial_prompt,
 781                                    cx,
 782                                )
 783                            })
 784                        }
 785                        InlineAssistTarget::Terminal(active_terminal) => {
 786                            TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 787                                assistant.assist(
 788                                    &active_terminal,
 789                                    Some(workspace),
 790                                    assistant_panel.upgrade().as_ref(),
 791                                    initial_prompt,
 792                                    cx,
 793                                )
 794                            })
 795                        }
 796                    })?
 797                } else {
 798                    workspace.update(&mut cx, |workspace, cx| {
 799                        workspace.focus_panel::<AssistantPanel>(cx)
 800                    })?;
 801                }
 802
 803                anyhow::Ok(())
 804            })
 805            .detach_and_log_err(cx)
 806        }
 807    }
 808
 809    fn resolve_inline_assist_target(
 810        workspace: &mut Workspace,
 811        assistant_panel: &View<AssistantPanel>,
 812        cx: &mut WindowContext,
 813    ) -> Option<InlineAssistTarget> {
 814        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
 815            if terminal_panel
 816                .read(cx)
 817                .focus_handle(cx)
 818                .contains_focused(cx)
 819            {
 820                if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
 821                    pane.read(cx)
 822                        .active_item()
 823                        .and_then(|t| t.downcast::<TerminalView>())
 824                }) {
 825                    return Some(InlineAssistTarget::Terminal(terminal_view));
 826                }
 827            }
 828        }
 829        let context_editor =
 830            assistant_panel
 831                .read(cx)
 832                .active_context_editor(cx)
 833                .and_then(|editor| {
 834                    let editor = &editor.read(cx).editor;
 835                    if editor.read(cx).is_focused(cx) {
 836                        Some(editor.clone())
 837                    } else {
 838                        None
 839                    }
 840                });
 841
 842        if let Some(context_editor) = context_editor {
 843            Some(InlineAssistTarget::Editor(context_editor, false))
 844        } else if let Some(workspace_editor) = workspace
 845            .active_item(cx)
 846            .and_then(|item| item.act_as::<Editor>(cx))
 847        {
 848            Some(InlineAssistTarget::Editor(workspace_editor, true))
 849        } else if let Some(terminal_view) = workspace
 850            .active_item(cx)
 851            .and_then(|item| item.act_as::<TerminalView>(cx))
 852        {
 853            Some(InlineAssistTarget::Terminal(terminal_view))
 854        } else {
 855            None
 856        }
 857    }
 858
 859    fn new_context(&mut self, cx: &mut ViewContext<Self>) -> Option<View<ContextEditor>> {
 860        if self.project.read(cx).is_remote() {
 861            let task = self
 862                .context_store
 863                .update(cx, |store, cx| store.create_remote_context(cx));
 864
 865            cx.spawn(|this, mut cx| async move {
 866                let context = task.await?;
 867
 868                this.update(&mut cx, |this, cx| {
 869                    let workspace = this.workspace.clone();
 870                    let project = this.project.clone();
 871                    let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err();
 872
 873                    let fs = this.fs.clone();
 874                    let project = this.project.clone();
 875                    let weak_assistant_panel = cx.view().downgrade();
 876
 877                    let editor = cx.new_view(|cx| {
 878                        ContextEditor::for_context(
 879                            context,
 880                            fs,
 881                            workspace,
 882                            project,
 883                            lsp_adapter_delegate,
 884                            weak_assistant_panel,
 885                            cx,
 886                        )
 887                    });
 888
 889                    this.show_context(editor, cx);
 890
 891                    anyhow::Ok(())
 892                })??;
 893
 894                anyhow::Ok(())
 895            })
 896            .detach_and_log_err(cx);
 897
 898            None
 899        } else {
 900            let context = self.context_store.update(cx, |store, cx| store.create(cx));
 901            let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx).log_err();
 902
 903            let assistant_panel = cx.view().downgrade();
 904            let editor = cx.new_view(|cx| {
 905                let mut editor = ContextEditor::for_context(
 906                    context,
 907                    self.fs.clone(),
 908                    self.workspace.clone(),
 909                    self.project.clone(),
 910                    lsp_adapter_delegate,
 911                    assistant_panel,
 912                    cx,
 913                );
 914                editor.insert_default_prompt(cx);
 915                editor
 916            });
 917
 918            self.show_context(editor.clone(), cx);
 919            Some(editor)
 920        }
 921    }
 922
 923    fn show_context(&mut self, context_editor: View<ContextEditor>, cx: &mut ViewContext<Self>) {
 924        let focus = self.focus_handle(cx).contains_focused(cx);
 925        let prev_len = self.pane.read(cx).items_len();
 926        self.pane.update(cx, |pane, cx| {
 927            pane.add_item(Box::new(context_editor.clone()), focus, focus, None, cx)
 928        });
 929
 930        if prev_len != self.pane.read(cx).items_len() {
 931            self.subscriptions
 932                .push(cx.subscribe(&context_editor, Self::handle_context_editor_event));
 933        }
 934
 935        self.show_updated_summary(&context_editor, cx);
 936
 937        cx.emit(AssistantPanelEvent::ContextEdited);
 938        cx.notify();
 939    }
 940
 941    fn show_updated_summary(
 942        &self,
 943        context_editor: &View<ContextEditor>,
 944        cx: &mut ViewContext<Self>,
 945    ) {
 946        context_editor.update(cx, |context_editor, cx| {
 947            let new_summary = context_editor.title(cx).to_string();
 948            self.model_summary_editor.update(cx, |summary_editor, cx| {
 949                if summary_editor.text(cx) != new_summary {
 950                    summary_editor.set_text(new_summary, cx);
 951                }
 952            });
 953        });
 954    }
 955
 956    fn handle_context_editor_event(
 957        &mut self,
 958        context_editor: View<ContextEditor>,
 959        event: &EditorEvent,
 960        cx: &mut ViewContext<Self>,
 961    ) {
 962        match event {
 963            EditorEvent::TitleChanged => {
 964                self.show_updated_summary(&context_editor, cx);
 965                cx.notify()
 966            }
 967            EditorEvent::Edited { .. } => cx.emit(AssistantPanelEvent::ContextEdited),
 968            _ => {}
 969        }
 970    }
 971
 972    fn show_configuration(
 973        workspace: &mut Workspace,
 974        _: &ShowConfiguration,
 975        cx: &mut ViewContext<Workspace>,
 976    ) {
 977        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
 978            return;
 979        };
 980
 981        if !panel.focus_handle(cx).contains_focused(cx) {
 982            workspace.toggle_panel_focus::<AssistantPanel>(cx);
 983        }
 984
 985        panel.update(cx, |this, cx| {
 986            this.show_configuration_tab(cx);
 987        })
 988    }
 989
 990    fn show_configuration_tab(&mut self, cx: &mut ViewContext<Self>) {
 991        let configuration_item_ix = self
 992            .pane
 993            .read(cx)
 994            .items()
 995            .position(|item| item.downcast::<ConfigurationView>().is_some());
 996
 997        if let Some(configuration_item_ix) = configuration_item_ix {
 998            self.pane.update(cx, |pane, cx| {
 999                pane.activate_item(configuration_item_ix, true, true, cx);
1000            });
1001        } else {
1002            let configuration = cx.new_view(|cx| ConfigurationView::new(cx));
1003            self.configuration_subscription = Some(cx.subscribe(
1004                &configuration,
1005                |this, _, event: &ConfigurationViewEvent, cx| match event {
1006                    ConfigurationViewEvent::NewProviderContextEditor(provider) => {
1007                        if LanguageModelRegistry::read_global(cx)
1008                            .active_provider()
1009                            .map_or(true, |p| p.id() != provider.id())
1010                        {
1011                            if let Some(model) = provider.provided_models(cx).first().cloned() {
1012                                update_settings_file::<AssistantSettings>(
1013                                    this.fs.clone(),
1014                                    cx,
1015                                    move |settings, _| settings.set_model(model),
1016                                );
1017                            }
1018                        }
1019
1020                        this.new_context(cx);
1021                    }
1022                },
1023            ));
1024            self.pane.update(cx, |pane, cx| {
1025                pane.add_item(Box::new(configuration), true, true, None, cx);
1026            });
1027        }
1028    }
1029
1030    fn deploy_history(&mut self, _: &DeployHistory, cx: &mut ViewContext<Self>) {
1031        let history_item_ix = self
1032            .pane
1033            .read(cx)
1034            .items()
1035            .position(|item| item.downcast::<ContextHistory>().is_some());
1036
1037        if let Some(history_item_ix) = history_item_ix {
1038            self.pane.update(cx, |pane, cx| {
1039                pane.activate_item(history_item_ix, true, true, cx);
1040            });
1041        } else {
1042            let assistant_panel = cx.view().downgrade();
1043            let history = cx.new_view(|cx| {
1044                ContextHistory::new(
1045                    self.project.clone(),
1046                    self.context_store.clone(),
1047                    assistant_panel,
1048                    cx,
1049                )
1050            });
1051            self.pane.update(cx, |pane, cx| {
1052                pane.add_item(Box::new(history), true, true, None, cx);
1053            });
1054        }
1055    }
1056
1057    fn deploy_prompt_library(&mut self, _: &DeployPromptLibrary, cx: &mut ViewContext<Self>) {
1058        open_prompt_library(self.languages.clone(), cx).detach_and_log_err(cx);
1059    }
1060
1061    fn toggle_model_selector(&mut self, _: &ToggleModelSelector, cx: &mut ViewContext<Self>) {
1062        self.model_selector_menu_handle.toggle(cx);
1063    }
1064
1065    fn active_context_editor(&self, cx: &AppContext) -> Option<View<ContextEditor>> {
1066        self.pane
1067            .read(cx)
1068            .active_item()?
1069            .downcast::<ContextEditor>()
1070    }
1071
1072    pub fn active_context(&self, cx: &AppContext) -> Option<Model<Context>> {
1073        Some(self.active_context_editor(cx)?.read(cx).context.clone())
1074    }
1075
1076    fn open_saved_context(
1077        &mut self,
1078        path: PathBuf,
1079        cx: &mut ViewContext<Self>,
1080    ) -> Task<Result<()>> {
1081        let existing_context = self.pane.read(cx).items().find_map(|item| {
1082            item.downcast::<ContextEditor>()
1083                .filter(|editor| editor.read(cx).context.read(cx).path() == Some(&path))
1084        });
1085        if let Some(existing_context) = existing_context {
1086            return cx.spawn(|this, mut cx| async move {
1087                this.update(&mut cx, |this, cx| this.show_context(existing_context, cx))
1088            });
1089        }
1090
1091        let context = self
1092            .context_store
1093            .update(cx, |store, cx| store.open_local_context(path.clone(), cx));
1094        let fs = self.fs.clone();
1095        let project = self.project.clone();
1096        let workspace = self.workspace.clone();
1097
1098        let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err();
1099
1100        cx.spawn(|this, mut cx| async move {
1101            let context = context.await?;
1102            let assistant_panel = this.clone();
1103            this.update(&mut cx, |this, cx| {
1104                let editor = cx.new_view(|cx| {
1105                    ContextEditor::for_context(
1106                        context,
1107                        fs,
1108                        workspace,
1109                        project,
1110                        lsp_adapter_delegate,
1111                        assistant_panel,
1112                        cx,
1113                    )
1114                });
1115                this.show_context(editor, cx);
1116                anyhow::Ok(())
1117            })??;
1118            Ok(())
1119        })
1120    }
1121
1122    fn open_remote_context(
1123        &mut self,
1124        id: ContextId,
1125        cx: &mut ViewContext<Self>,
1126    ) -> Task<Result<View<ContextEditor>>> {
1127        let existing_context = self.pane.read(cx).items().find_map(|item| {
1128            item.downcast::<ContextEditor>()
1129                .filter(|editor| *editor.read(cx).context.read(cx).id() == id)
1130        });
1131        if let Some(existing_context) = existing_context {
1132            return cx.spawn(|this, mut cx| async move {
1133                this.update(&mut cx, |this, cx| {
1134                    this.show_context(existing_context.clone(), cx)
1135                })?;
1136                Ok(existing_context)
1137            });
1138        }
1139
1140        let context = self
1141            .context_store
1142            .update(cx, |store, cx| store.open_remote_context(id, cx));
1143        let fs = self.fs.clone();
1144        let workspace = self.workspace.clone();
1145        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx).log_err();
1146
1147        cx.spawn(|this, mut cx| async move {
1148            let context = context.await?;
1149            let assistant_panel = this.clone();
1150            this.update(&mut cx, |this, cx| {
1151                let editor = cx.new_view(|cx| {
1152                    ContextEditor::for_context(
1153                        context,
1154                        fs,
1155                        workspace,
1156                        this.project.clone(),
1157                        lsp_adapter_delegate,
1158                        assistant_panel,
1159                        cx,
1160                    )
1161                });
1162                this.show_context(editor.clone(), cx);
1163                anyhow::Ok(editor)
1164            })?
1165        })
1166    }
1167
1168    fn is_authenticated(&mut self, cx: &mut ViewContext<Self>) -> bool {
1169        LanguageModelRegistry::read_global(cx)
1170            .active_provider()
1171            .map_or(false, |provider| provider.is_authenticated(cx))
1172    }
1173
1174    fn authenticate(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
1175        LanguageModelRegistry::read_global(cx)
1176            .active_provider()
1177            .map_or(
1178                Task::ready(Err(anyhow!("no active language model provider"))),
1179                |provider| provider.authenticate(cx),
1180            )
1181    }
1182}
1183
1184impl Render for AssistantPanel {
1185    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1186        let mut registrar = DivRegistrar::new(
1187            |panel, cx| {
1188                panel
1189                    .pane
1190                    .read(cx)
1191                    .toolbar()
1192                    .read(cx)
1193                    .item_of_type::<BufferSearchBar>()
1194            },
1195            cx,
1196        );
1197        BufferSearchBar::register(&mut registrar);
1198        let registrar = registrar.into_div();
1199
1200        v_flex()
1201            .key_context("AssistantPanel")
1202            .size_full()
1203            .on_action(cx.listener(|this, _: &workspace::NewFile, cx| {
1204                this.new_context(cx);
1205            }))
1206            .on_action(
1207                cx.listener(|this, _: &ShowConfiguration, cx| this.show_configuration_tab(cx)),
1208            )
1209            .on_action(cx.listener(AssistantPanel::deploy_history))
1210            .on_action(cx.listener(AssistantPanel::deploy_prompt_library))
1211            .on_action(cx.listener(AssistantPanel::toggle_model_selector))
1212            .child(registrar.size_full().child(self.pane.clone()))
1213            .into_any_element()
1214    }
1215}
1216
1217impl Panel for AssistantPanel {
1218    fn persistent_name() -> &'static str {
1219        "AssistantPanel"
1220    }
1221
1222    fn position(&self, cx: &WindowContext) -> DockPosition {
1223        match AssistantSettings::get_global(cx).dock {
1224            AssistantDockPosition::Left => DockPosition::Left,
1225            AssistantDockPosition::Bottom => DockPosition::Bottom,
1226            AssistantDockPosition::Right => DockPosition::Right,
1227        }
1228    }
1229
1230    fn position_is_valid(&self, _: DockPosition) -> bool {
1231        true
1232    }
1233
1234    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1235        settings::update_settings_file::<AssistantSettings>(
1236            self.fs.clone(),
1237            cx,
1238            move |settings, _| {
1239                let dock = match position {
1240                    DockPosition::Left => AssistantDockPosition::Left,
1241                    DockPosition::Bottom => AssistantDockPosition::Bottom,
1242                    DockPosition::Right => AssistantDockPosition::Right,
1243                };
1244                settings.set_dock(dock);
1245            },
1246        );
1247    }
1248
1249    fn size(&self, cx: &WindowContext) -> Pixels {
1250        let settings = AssistantSettings::get_global(cx);
1251        match self.position(cx) {
1252            DockPosition::Left | DockPosition::Right => {
1253                self.width.unwrap_or(settings.default_width)
1254            }
1255            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1256        }
1257    }
1258
1259    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1260        match self.position(cx) {
1261            DockPosition::Left | DockPosition::Right => self.width = size,
1262            DockPosition::Bottom => self.height = size,
1263        }
1264        cx.notify();
1265    }
1266
1267    fn is_zoomed(&self, cx: &WindowContext) -> bool {
1268        self.pane.read(cx).is_zoomed()
1269    }
1270
1271    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1272        self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
1273    }
1274
1275    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1276        if active {
1277            if self.pane.read(cx).items_len() == 0 {
1278                self.new_context(cx);
1279            }
1280
1281            self.ensure_authenticated(cx);
1282        }
1283    }
1284
1285    fn pane(&self) -> Option<View<Pane>> {
1286        Some(self.pane.clone())
1287    }
1288
1289    fn remote_id() -> Option<proto::PanelId> {
1290        Some(proto::PanelId::AssistantPanel)
1291    }
1292
1293    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
1294        let settings = AssistantSettings::get_global(cx);
1295        if !settings.enabled || !settings.button {
1296            return None;
1297        }
1298
1299        Some(IconName::ZedAssistant)
1300    }
1301
1302    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1303        Some("Assistant Panel")
1304    }
1305
1306    fn toggle_action(&self) -> Box<dyn Action> {
1307        Box::new(ToggleFocus)
1308    }
1309}
1310
1311impl EventEmitter<PanelEvent> for AssistantPanel {}
1312impl EventEmitter<AssistantPanelEvent> for AssistantPanel {}
1313
1314impl FocusableView for AssistantPanel {
1315    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1316        self.pane.focus_handle(cx)
1317    }
1318}
1319
1320pub enum ContextEditorEvent {
1321    Edited,
1322    TabContentChanged,
1323}
1324
1325#[derive(Copy, Clone, Debug, PartialEq)]
1326struct ScrollPosition {
1327    offset_before_cursor: gpui::Point<f32>,
1328    cursor: Anchor,
1329}
1330
1331struct WorkflowAssist {
1332    editor: WeakView<Editor>,
1333    editor_was_open: bool,
1334    assist_ids: Vec<InlineAssistId>,
1335}
1336
1337pub struct ContextEditor {
1338    context: Model<Context>,
1339    fs: Arc<dyn Fs>,
1340    workspace: WeakView<Workspace>,
1341    project: Model<Project>,
1342    lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1343    editor: View<Editor>,
1344    blocks: HashSet<CustomBlockId>,
1345    scroll_position: Option<ScrollPosition>,
1346    remote_id: Option<workspace::ViewId>,
1347    pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
1348    pending_slash_command_blocks: HashMap<Range<language::Anchor>, CustomBlockId>,
1349    workflow_assists: HashMap<Range<language::Anchor>, WorkflowAssist>,
1350    active_workflow_step_range: Option<Range<language::Anchor>>,
1351    _subscriptions: Vec<Subscription>,
1352    assistant_panel: WeakView<AssistantPanel>,
1353    error_message: Option<SharedString>,
1354}
1355
1356const DEFAULT_TAB_TITLE: &str = "New Context";
1357const MAX_TAB_TITLE_LEN: usize = 16;
1358
1359impl ContextEditor {
1360    fn for_context(
1361        context: Model<Context>,
1362        fs: Arc<dyn Fs>,
1363        workspace: WeakView<Workspace>,
1364        project: Model<Project>,
1365        lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1366        assistant_panel: WeakView<AssistantPanel>,
1367        cx: &mut ViewContext<Self>,
1368    ) -> Self {
1369        let completion_provider = SlashCommandCompletionProvider::new(
1370            Some(cx.view().downgrade()),
1371            Some(workspace.clone()),
1372        );
1373
1374        let editor = cx.new_view(|cx| {
1375            let mut editor = Editor::for_buffer(context.read(cx).buffer().clone(), None, cx);
1376            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
1377            editor.set_show_line_numbers(false, cx);
1378            editor.set_show_git_diff_gutter(false, cx);
1379            editor.set_show_code_actions(false, cx);
1380            editor.set_show_runnables(false, cx);
1381            editor.set_show_wrap_guides(false, cx);
1382            editor.set_show_indent_guides(false, cx);
1383            editor.set_completion_provider(Box::new(completion_provider));
1384            editor.set_collaboration_hub(Box::new(project.clone()));
1385            editor
1386        });
1387
1388        let _subscriptions = vec![
1389            cx.observe(&context, |_, _, cx| cx.notify()),
1390            cx.subscribe(&context, Self::handle_context_event),
1391            cx.subscribe(&editor, Self::handle_editor_event),
1392            cx.subscribe(&editor, Self::handle_editor_search_event),
1393        ];
1394
1395        let sections = context.read(cx).slash_command_output_sections().to_vec();
1396        let mut this = Self {
1397            context,
1398            editor,
1399            lsp_adapter_delegate,
1400            blocks: Default::default(),
1401            scroll_position: None,
1402            remote_id: None,
1403            fs,
1404            workspace,
1405            project,
1406            pending_slash_command_creases: HashMap::default(),
1407            pending_slash_command_blocks: HashMap::default(),
1408            _subscriptions,
1409            workflow_assists: HashMap::default(),
1410            active_workflow_step_range: None,
1411            assistant_panel,
1412            error_message: None,
1413        };
1414        this.update_message_headers(cx);
1415        this.insert_slash_command_output_sections(sections, cx);
1416        this
1417    }
1418
1419    fn insert_default_prompt(&mut self, cx: &mut ViewContext<Self>) {
1420        let command_name = DefaultSlashCommand.name();
1421        self.editor.update(cx, |editor, cx| {
1422            editor.insert(&format!("/{command_name}"), cx)
1423        });
1424        self.split(&Split, cx);
1425        let command = self.context.update(cx, |context, cx| {
1426            let first_message_id = context.messages(cx).next().unwrap().id;
1427            context.update_metadata(first_message_id, cx, |metadata| {
1428                metadata.role = Role::System;
1429            });
1430            context.reparse_slash_commands(cx);
1431            context.pending_slash_commands()[0].clone()
1432        });
1433
1434        self.run_command(
1435            command.source_range,
1436            &command.name,
1437            command.argument.as_deref(),
1438            false,
1439            self.workspace.clone(),
1440            cx,
1441        );
1442    }
1443
1444    fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
1445        if !self.apply_workflow_step(cx) {
1446            self.error_message = None;
1447            self.send_to_model(cx);
1448            cx.notify();
1449        }
1450    }
1451
1452    fn apply_workflow_step(&mut self, cx: &mut ViewContext<Self>) -> bool {
1453        if let Some(step_range) = self.active_workflow_step_range.as_ref() {
1454            if let Some(assists) = self.workflow_assists.get(&step_range) {
1455                let assist_ids = assists.assist_ids.clone();
1456                cx.window_context().defer(|cx| {
1457                    InlineAssistant::update_global(cx, |assistant, cx| {
1458                        for assist_id in assist_ids {
1459                            assistant.start_assist(assist_id, cx);
1460                        }
1461                    })
1462                });
1463
1464                !assists.assist_ids.is_empty()
1465            } else {
1466                false
1467            }
1468        } else {
1469            false
1470        }
1471    }
1472
1473    fn send_to_model(&mut self, cx: &mut ViewContext<Self>) {
1474        if let Some(user_message) = self.context.update(cx, |context, cx| context.assist(cx)) {
1475            let new_selection = {
1476                let cursor = user_message
1477                    .start
1478                    .to_offset(self.context.read(cx).buffer().read(cx));
1479                cursor..cursor
1480            };
1481            self.editor.update(cx, |editor, cx| {
1482                editor.change_selections(
1483                    Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
1484                    cx,
1485                    |selections| selections.select_ranges([new_selection]),
1486                );
1487            });
1488            // Avoid scrolling to the new cursor position so the assistant's output is stable.
1489            cx.defer(|this, _| this.scroll_position = None);
1490        }
1491    }
1492
1493    fn cancel_last_assist(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1494        if !self
1495            .context
1496            .update(cx, |context, _| context.cancel_last_assist())
1497        {
1498            cx.propagate();
1499        }
1500    }
1501
1502    fn debug_edit_steps(&mut self, _: &DebugEditSteps, cx: &mut ViewContext<Self>) {
1503        let mut output = String::new();
1504        for (i, step) in self.context.read(cx).workflow_steps().iter().enumerate() {
1505            output.push_str(&format!("Step {}:\n", i + 1));
1506            output.push_str(&format!(
1507                "Content: {}\n",
1508                self.context
1509                    .read(cx)
1510                    .buffer()
1511                    .read(cx)
1512                    .text_for_range(step.tagged_range.clone())
1513                    .collect::<String>()
1514            ));
1515            match &step.status {
1516                WorkflowStepStatus::Resolved(ResolvedWorkflowStep { title, suggestions }) => {
1517                    output.push_str("Resolution:\n");
1518                    output.push_str(&format!("  {:?}\n", title));
1519                    output.push_str(&format!("  {:?}\n", suggestions));
1520                }
1521                WorkflowStepStatus::Pending(_) => {
1522                    output.push_str("Resolution: Pending\n");
1523                }
1524            }
1525            output.push('\n');
1526        }
1527
1528        let editor = self
1529            .workspace
1530            .update(cx, |workspace, cx| Editor::new_in_workspace(workspace, cx));
1531
1532        if let Ok(editor) = editor {
1533            cx.spawn(|_, mut cx| async move {
1534                let editor = editor.await?;
1535                editor.update(&mut cx, |editor, cx| editor.set_text(output, cx))
1536            })
1537            .detach_and_notify_err(cx);
1538        }
1539    }
1540
1541    fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
1542        let cursors = self.cursors(cx);
1543        self.context.update(cx, |context, cx| {
1544            let messages = context
1545                .messages_for_offsets(cursors, cx)
1546                .into_iter()
1547                .map(|message| message.id)
1548                .collect();
1549            context.cycle_message_roles(messages, cx)
1550        });
1551    }
1552
1553    fn cursors(&self, cx: &AppContext) -> Vec<usize> {
1554        let selections = self.editor.read(cx).selections.all::<usize>(cx);
1555        selections
1556            .into_iter()
1557            .map(|selection| selection.head())
1558            .collect()
1559    }
1560
1561    fn insert_command(&mut self, name: &str, cx: &mut ViewContext<Self>) {
1562        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1563            self.editor.update(cx, |editor, cx| {
1564                editor.transact(cx, |editor, cx| {
1565                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel());
1566                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1567                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
1568                    if newest_cursor.column > 0
1569                        || snapshot
1570                            .chars_at(newest_cursor)
1571                            .next()
1572                            .map_or(false, |ch| ch != '\n')
1573                    {
1574                        editor.move_to_end_of_line(
1575                            &MoveToEndOfLine {
1576                                stop_at_soft_wraps: false,
1577                            },
1578                            cx,
1579                        );
1580                        editor.newline(&Newline, cx);
1581                    }
1582
1583                    editor.insert(&format!("/{name}"), cx);
1584                    if command.requires_argument() {
1585                        editor.insert(" ", cx);
1586                        editor.show_completions(&ShowCompletions::default(), cx);
1587                    }
1588                });
1589            });
1590            if !command.requires_argument() {
1591                self.confirm_command(&ConfirmCommand, cx);
1592            }
1593        }
1594    }
1595
1596    pub fn confirm_command(&mut self, _: &ConfirmCommand, cx: &mut ViewContext<Self>) {
1597        let selections = self.editor.read(cx).selections.disjoint_anchors();
1598        let mut commands_by_range = HashMap::default();
1599        let workspace = self.workspace.clone();
1600        self.context.update(cx, |context, cx| {
1601            context.reparse_slash_commands(cx);
1602            for selection in selections.iter() {
1603                if let Some(command) =
1604                    context.pending_command_for_position(selection.head().text_anchor, cx)
1605                {
1606                    commands_by_range
1607                        .entry(command.source_range.clone())
1608                        .or_insert_with(|| command.clone());
1609                }
1610            }
1611        });
1612
1613        if commands_by_range.is_empty() {
1614            cx.propagate();
1615        } else {
1616            for command in commands_by_range.into_values() {
1617                self.run_command(
1618                    command.source_range,
1619                    &command.name,
1620                    command.argument.as_deref(),
1621                    true,
1622                    workspace.clone(),
1623                    cx,
1624                );
1625            }
1626            cx.stop_propagation();
1627        }
1628    }
1629
1630    pub fn run_command(
1631        &mut self,
1632        command_range: Range<language::Anchor>,
1633        name: &str,
1634        argument: Option<&str>,
1635        insert_trailing_newline: bool,
1636        workspace: WeakView<Workspace>,
1637        cx: &mut ViewContext<Self>,
1638    ) {
1639        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1640            let argument = argument.map(ToString::to_string);
1641            let output = command.run(
1642                argument.as_deref(),
1643                workspace,
1644                self.lsp_adapter_delegate.clone(),
1645                cx,
1646            );
1647            self.context.update(cx, |context, cx| {
1648                context.insert_command_output(command_range, output, insert_trailing_newline, cx)
1649            });
1650        }
1651    }
1652
1653    fn handle_context_event(
1654        &mut self,
1655        _: Model<Context>,
1656        event: &ContextEvent,
1657        cx: &mut ViewContext<Self>,
1658    ) {
1659        let context_editor = cx.view().downgrade();
1660
1661        match event {
1662            ContextEvent::MessagesEdited => {
1663                self.update_message_headers(cx);
1664                self.context.update(cx, |context, cx| {
1665                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1666                });
1667            }
1668            ContextEvent::WorkflowStepsChanged => {
1669                self.update_active_workflow_step_from_cursor(cx);
1670                cx.notify();
1671            }
1672            ContextEvent::SummaryChanged => {
1673                cx.emit(EditorEvent::TitleChanged);
1674                self.context.update(cx, |context, cx| {
1675                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1676                });
1677            }
1678            ContextEvent::StreamedCompletion => {
1679                self.editor.update(cx, |editor, cx| {
1680                    if let Some(scroll_position) = self.scroll_position {
1681                        let snapshot = editor.snapshot(cx);
1682                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
1683                        let scroll_top =
1684                            cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
1685                        editor.set_scroll_position(
1686                            point(scroll_position.offset_before_cursor.x, scroll_top),
1687                            cx,
1688                        );
1689                    }
1690                });
1691            }
1692            ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
1693                self.editor.update(cx, |editor, cx| {
1694                    let buffer = editor.buffer().read(cx).snapshot(cx);
1695                    let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
1696                    let excerpt_id = *excerpt_id;
1697
1698                    editor.remove_creases(
1699                        removed
1700                            .iter()
1701                            .filter_map(|range| self.pending_slash_command_creases.remove(range)),
1702                        cx,
1703                    );
1704
1705                    editor.remove_blocks(
1706                        HashSet::from_iter(
1707                            removed.iter().filter_map(|range| {
1708                                self.pending_slash_command_blocks.remove(range)
1709                            }),
1710                        ),
1711                        None,
1712                        cx,
1713                    );
1714
1715                    let crease_ids = editor.insert_creases(
1716                        updated.iter().map(|command| {
1717                            let workspace = self.workspace.clone();
1718                            let confirm_command = Arc::new({
1719                                let context_editor = context_editor.clone();
1720                                let command = command.clone();
1721                                move |cx: &mut WindowContext| {
1722                                    context_editor
1723                                        .update(cx, |context_editor, cx| {
1724                                            context_editor.run_command(
1725                                                command.source_range.clone(),
1726                                                &command.name,
1727                                                command.argument.as_deref(),
1728                                                false,
1729                                                workspace.clone(),
1730                                                cx,
1731                                            );
1732                                        })
1733                                        .ok();
1734                                }
1735                            });
1736                            let placeholder = FoldPlaceholder {
1737                                render: Arc::new(move |_, _, _| Empty.into_any()),
1738                                constrain_width: false,
1739                                merge_adjacent: false,
1740                            };
1741                            let render_toggle = {
1742                                let confirm_command = confirm_command.clone();
1743                                let command = command.clone();
1744                                move |row, _, _, _cx: &mut WindowContext| {
1745                                    render_pending_slash_command_gutter_decoration(
1746                                        row,
1747                                        &command.status,
1748                                        confirm_command.clone(),
1749                                    )
1750                                }
1751                            };
1752                            let render_trailer = {
1753                                let command = command.clone();
1754                                move |row, _unfold, cx: &mut WindowContext| {
1755                                    // TODO: In the future we should investigate how we can expose
1756                                    // this as a hook on the `SlashCommand` trait so that we don't
1757                                    // need to special-case it here.
1758                                    if command.name == DocsSlashCommand::NAME {
1759                                        return render_docs_slash_command_trailer(
1760                                            row,
1761                                            command.clone(),
1762                                            cx,
1763                                        );
1764                                    }
1765
1766                                    Empty.into_any()
1767                                }
1768                            };
1769
1770                            let start = buffer
1771                                .anchor_in_excerpt(excerpt_id, command.source_range.start)
1772                                .unwrap();
1773                            let end = buffer
1774                                .anchor_in_excerpt(excerpt_id, command.source_range.end)
1775                                .unwrap();
1776                            Crease::new(start..end, placeholder, render_toggle, render_trailer)
1777                        }),
1778                        cx,
1779                    );
1780
1781                    let block_ids = editor.insert_blocks(
1782                        updated
1783                            .iter()
1784                            .filter_map(|command| match &command.status {
1785                                PendingSlashCommandStatus::Error(error) => {
1786                                    Some((command, error.clone()))
1787                                }
1788                                _ => None,
1789                            })
1790                            .map(|(command, error_message)| BlockProperties {
1791                                style: BlockStyle::Fixed,
1792                                position: Anchor {
1793                                    buffer_id: Some(buffer_id),
1794                                    excerpt_id,
1795                                    text_anchor: command.source_range.start,
1796                                },
1797                                height: 1,
1798                                disposition: BlockDisposition::Below,
1799                                render: slash_command_error_block_renderer(error_message),
1800                            }),
1801                        None,
1802                        cx,
1803                    );
1804
1805                    self.pending_slash_command_creases.extend(
1806                        updated
1807                            .iter()
1808                            .map(|command| command.source_range.clone())
1809                            .zip(crease_ids),
1810                    );
1811
1812                    self.pending_slash_command_blocks.extend(
1813                        updated
1814                            .iter()
1815                            .map(|command| command.source_range.clone())
1816                            .zip(block_ids),
1817                    );
1818                })
1819            }
1820            ContextEvent::SlashCommandFinished {
1821                output_range,
1822                sections,
1823                run_commands_in_output,
1824            } => {
1825                self.insert_slash_command_output_sections(sections.iter().cloned(), cx);
1826
1827                if *run_commands_in_output {
1828                    let commands = self.context.update(cx, |context, cx| {
1829                        context.reparse_slash_commands(cx);
1830                        context
1831                            .pending_commands_for_range(output_range.clone(), cx)
1832                            .to_vec()
1833                    });
1834
1835                    for command in commands {
1836                        self.run_command(
1837                            command.source_range,
1838                            &command.name,
1839                            command.argument.as_deref(),
1840                            false,
1841                            self.workspace.clone(),
1842                            cx,
1843                        );
1844                    }
1845                }
1846            }
1847            ContextEvent::Operation(_) => {}
1848            ContextEvent::AssistError(error_message) => {
1849                self.error_message = Some(SharedString::from(error_message.clone()));
1850            }
1851        }
1852    }
1853
1854    fn insert_slash_command_output_sections(
1855        &mut self,
1856        sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
1857        cx: &mut ViewContext<Self>,
1858    ) {
1859        self.editor.update(cx, |editor, cx| {
1860            let buffer = editor.buffer().read(cx).snapshot(cx);
1861            let excerpt_id = *buffer.as_singleton().unwrap().0;
1862            let mut buffer_rows_to_fold = BTreeSet::new();
1863            let mut creases = Vec::new();
1864            for section in sections {
1865                let start = buffer
1866                    .anchor_in_excerpt(excerpt_id, section.range.start)
1867                    .unwrap();
1868                let end = buffer
1869                    .anchor_in_excerpt(excerpt_id, section.range.end)
1870                    .unwrap();
1871                let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1872                buffer_rows_to_fold.insert(buffer_row);
1873                creases.push(Crease::new(
1874                    start..end,
1875                    FoldPlaceholder {
1876                        render: Arc::new({
1877                            let editor = cx.view().downgrade();
1878                            let icon = section.icon;
1879                            let label = section.label.clone();
1880                            move |fold_id, fold_range, _cx| {
1881                                let editor = editor.clone();
1882                                ButtonLike::new(fold_id)
1883                                    .style(ButtonStyle::Filled)
1884                                    .layer(ElevationIndex::ElevatedSurface)
1885                                    .child(Icon::new(icon))
1886                                    .child(Label::new(label.clone()).single_line())
1887                                    .on_click(move |_, cx| {
1888                                        editor
1889                                            .update(cx, |editor, cx| {
1890                                                let buffer_start = fold_range
1891                                                    .start
1892                                                    .to_point(&editor.buffer().read(cx).read(cx));
1893                                                let buffer_row = MultiBufferRow(buffer_start.row);
1894                                                editor.unfold_at(&UnfoldAt { buffer_row }, cx);
1895                                            })
1896                                            .ok();
1897                                    })
1898                                    .into_any_element()
1899                            }
1900                        }),
1901                        constrain_width: false,
1902                        merge_adjacent: false,
1903                    },
1904                    render_slash_command_output_toggle,
1905                    |_, _, _| Empty.into_any_element(),
1906                ));
1907            }
1908
1909            editor.insert_creases(creases, cx);
1910
1911            for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1912                editor.fold_at(&FoldAt { buffer_row }, cx);
1913            }
1914        });
1915    }
1916
1917    fn handle_editor_event(
1918        &mut self,
1919        _: View<Editor>,
1920        event: &EditorEvent,
1921        cx: &mut ViewContext<Self>,
1922    ) {
1923        match event {
1924            EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
1925                let cursor_scroll_position = self.cursor_scroll_position(cx);
1926                if *autoscroll {
1927                    self.scroll_position = cursor_scroll_position;
1928                } else if self.scroll_position != cursor_scroll_position {
1929                    self.scroll_position = None;
1930                }
1931            }
1932            EditorEvent::SelectionsChanged { .. } => {
1933                self.scroll_position = self.cursor_scroll_position(cx);
1934                self.update_active_workflow_step_from_cursor(cx);
1935            }
1936            _ => {}
1937        }
1938        cx.emit(event.clone());
1939    }
1940
1941    fn update_active_workflow_step_from_cursor(&mut self, cx: &mut ViewContext<Self>) {
1942        let new_step = self
1943            .workflow_step_range_for_cursor(cx)
1944            .as_ref()
1945            .and_then(|step_range| {
1946                let workflow_step = self
1947                    .context
1948                    .read(cx)
1949                    .workflow_step_for_range(step_range.clone())?;
1950                Some(workflow_step.tagged_range.clone())
1951            });
1952        if new_step.as_ref() != self.active_workflow_step_range.as_ref() {
1953            if let Some(old_step_range) = self.active_workflow_step_range.take() {
1954                self.hide_workflow_step(old_step_range, cx);
1955            }
1956
1957            if let Some(new_step) = new_step {
1958                self.activate_workflow_step(new_step, cx);
1959            }
1960        }
1961    }
1962
1963    fn hide_workflow_step(
1964        &mut self,
1965        step_range: Range<language::Anchor>,
1966        cx: &mut ViewContext<Self>,
1967    ) {
1968        let Some(step_assist) = self.workflow_assists.get_mut(&step_range) else {
1969            return;
1970        };
1971        let Some(editor) = step_assist.editor.upgrade() else {
1972            self.workflow_assists.remove(&step_range);
1973            return;
1974        };
1975
1976        InlineAssistant::update_global(cx, |assistant, cx| {
1977            step_assist.assist_ids.retain(|assist_id| {
1978                match assistant.status_for_assist(*assist_id, cx) {
1979                    Some(CodegenStatus::Idle) | None => {
1980                        assistant.finish_assist(*assist_id, true, cx);
1981                        false
1982                    }
1983                    _ => true,
1984                }
1985            });
1986        });
1987
1988        if step_assist.assist_ids.is_empty() {
1989            let editor_was_open = step_assist.editor_was_open;
1990            self.workflow_assists.remove(&step_range);
1991            self.workspace
1992                .update(cx, |workspace, cx| {
1993                    if let Some(pane) = workspace.pane_for(&editor) {
1994                        pane.update(cx, |pane, cx| {
1995                            let item_id = editor.entity_id();
1996                            if !editor_was_open && pane.is_active_preview_item(item_id) {
1997                                pane.close_item_by_id(item_id, SaveIntent::Skip, cx)
1998                                    .detach_and_log_err(cx);
1999                            }
2000                        });
2001                    }
2002                })
2003                .ok();
2004        }
2005    }
2006
2007    fn activate_workflow_step(
2008        &mut self,
2009        step_range: Range<language::Anchor>,
2010        cx: &mut ViewContext<Self>,
2011    ) -> Option<()> {
2012        if self.scroll_to_existing_workflow_assist(&step_range, cx) {
2013            return None;
2014        }
2015
2016        let step = self
2017            .workflow_step(&step_range, cx)
2018            .with_context(|| format!("could not find workflow step for range {:?}", step_range))
2019            .log_err()?;
2020        let Some(resolved) = step.status.as_resolved() else {
2021            return None;
2022        };
2023
2024        let title = resolved.title.clone();
2025        let suggestions = resolved.suggestions.clone();
2026
2027        if let Some((editor, assist_ids, editor_was_open)) = {
2028            let assistant_panel = self.assistant_panel.upgrade()?;
2029            if suggestions.is_empty() {
2030                return None;
2031            }
2032
2033            let editor;
2034            let mut editor_was_open = false;
2035            let mut suggestion_groups = Vec::new();
2036            if suggestions.len() == 1 && suggestions.values().next().unwrap().len() == 1 {
2037                // If there's only one buffer and one suggestion group, open it directly
2038                let (buffer, groups) = suggestions.into_iter().next().unwrap();
2039                let group = groups.into_iter().next().unwrap();
2040                editor = self
2041                    .workspace
2042                    .update(cx, |workspace, cx| {
2043                        let active_pane = workspace.active_pane().clone();
2044                        editor_was_open =
2045                            workspace.is_project_item_open::<Editor>(&active_pane, &buffer, cx);
2046                        workspace.open_project_item::<Editor>(active_pane, buffer, false, false, cx)
2047                    })
2048                    .log_err()?;
2049
2050                let (&excerpt_id, _, _) = editor
2051                    .read(cx)
2052                    .buffer()
2053                    .read(cx)
2054                    .read(cx)
2055                    .as_singleton()
2056                    .unwrap();
2057
2058                // Scroll the editor to the suggested assist
2059                editor.update(cx, |editor, cx| {
2060                    let multibuffer = editor.buffer().read(cx).snapshot(cx);
2061                    let (&excerpt_id, _, buffer) = multibuffer.as_singleton().unwrap();
2062                    let anchor = if group.context_range.start.to_offset(buffer) == 0 {
2063                        Anchor::min()
2064                    } else {
2065                        multibuffer
2066                            .anchor_in_excerpt(excerpt_id, group.context_range.start)
2067                            .unwrap()
2068                    };
2069
2070                    editor.set_scroll_anchor(
2071                        ScrollAnchor {
2072                            offset: gpui::Point::default(),
2073                            anchor,
2074                        },
2075                        cx,
2076                    );
2077                });
2078
2079                suggestion_groups.push((excerpt_id, group));
2080            } else {
2081                // If there are multiple buffers or suggestion groups, create a multibuffer
2082                let multibuffer = cx.new_model(|cx| {
2083                    let replica_id = self.project.read(cx).replica_id();
2084                    let mut multibuffer =
2085                        MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
2086                    for (buffer, groups) in suggestions {
2087                        let excerpt_ids = multibuffer.push_excerpts(
2088                            buffer,
2089                            groups.iter().map(|suggestion_group| ExcerptRange {
2090                                context: suggestion_group.context_range.clone(),
2091                                primary: None,
2092                            }),
2093                            cx,
2094                        );
2095                        suggestion_groups.extend(excerpt_ids.into_iter().zip(groups));
2096                    }
2097                    multibuffer
2098                });
2099
2100                editor = cx.new_view(|cx| {
2101                    Editor::for_multibuffer(multibuffer, Some(self.project.clone()), true, cx)
2102                });
2103                self.workspace
2104                    .update(cx, |workspace, cx| {
2105                        workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
2106                    })
2107                    .log_err()?;
2108            }
2109
2110            let mut assist_ids = Vec::new();
2111            for (excerpt_id, suggestion_group) in suggestion_groups {
2112                for suggestion in suggestion_group.suggestions {
2113                    assist_ids.extend(suggestion.show(
2114                        &editor,
2115                        excerpt_id,
2116                        &self.workspace,
2117                        &assistant_panel,
2118                        cx,
2119                    ));
2120                }
2121            }
2122
2123            if let Some(range) = self.active_workflow_step_range.clone() {
2124                self.workflow_assists.insert(
2125                    range,
2126                    WorkflowAssist {
2127                        assist_ids: assist_ids.clone(),
2128                        editor: editor.downgrade(),
2129                        editor_was_open,
2130                    },
2131                );
2132            }
2133
2134            Some((editor, assist_ids, editor_was_open))
2135        } {
2136            self.workflow_assists.insert(
2137                step_range.clone(),
2138                WorkflowAssist {
2139                    assist_ids,
2140                    editor_was_open,
2141                    editor: editor.downgrade(),
2142                },
2143            );
2144        }
2145
2146        self.active_workflow_step_range = Some(step_range);
2147
2148        Some(())
2149    }
2150
2151    fn active_workflow_step<'a>(&'a self, cx: &'a AppContext) -> Option<&'a crate::WorkflowStep> {
2152        self.active_workflow_step_range
2153            .as_ref()
2154            .and_then(|step_range| {
2155                self.context
2156                    .read(cx)
2157                    .workflow_step_for_range(step_range.clone())
2158            })
2159    }
2160
2161    fn workflow_step<'a>(
2162        &'a mut self,
2163        step_range: &Range<text::Anchor>,
2164        cx: &'a mut ViewContext<ContextEditor>,
2165    ) -> Option<&'a crate::WorkflowStep> {
2166        self.context
2167            .read(cx)
2168            .workflow_step_for_range(step_range.clone())
2169    }
2170
2171    fn scroll_to_existing_workflow_assist(
2172        &self,
2173        step_range: &Range<language::Anchor>,
2174        cx: &mut ViewContext<Self>,
2175    ) -> bool {
2176        let step_assists = match self.workflow_assists.get(step_range) {
2177            Some(assists) => assists,
2178            None => return false,
2179        };
2180        let editor = match step_assists.editor.upgrade() {
2181            Some(editor) => editor,
2182            None => return false,
2183        };
2184        for assist_id in &step_assists.assist_ids {
2185            match InlineAssistant::global(cx).status_for_assist(*assist_id, cx) {
2186                Some(CodegenStatus::Idle) | None => {}
2187                _ => {
2188                    self.workspace
2189                        .update(cx, |workspace, cx| {
2190                            workspace.activate_item(&editor, false, false, cx);
2191                        })
2192                        .ok();
2193                    InlineAssistant::update_global(cx, |assistant, cx| {
2194                        assistant.scroll_to_assist(*assist_id, cx)
2195                    });
2196                    return true;
2197                }
2198            }
2199        }
2200        false
2201    }
2202
2203    fn handle_editor_search_event(
2204        &mut self,
2205        _: View<Editor>,
2206        event: &SearchEvent,
2207        cx: &mut ViewContext<Self>,
2208    ) {
2209        cx.emit(event.clone());
2210    }
2211
2212    fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2213        self.editor.update(cx, |editor, cx| {
2214            let snapshot = editor.snapshot(cx);
2215            let cursor = editor.selections.newest_anchor().head();
2216            let cursor_row = cursor
2217                .to_display_point(&snapshot.display_snapshot)
2218                .row()
2219                .as_f32();
2220            let scroll_position = editor
2221                .scroll_manager
2222                .anchor()
2223                .scroll_position(&snapshot.display_snapshot);
2224
2225            let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2226            if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2227                Some(ScrollPosition {
2228                    cursor,
2229                    offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2230                })
2231            } else {
2232                None
2233            }
2234        })
2235    }
2236
2237    fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2238        self.editor.update(cx, |editor, cx| {
2239            let buffer = editor.buffer().read(cx).snapshot(cx);
2240            let excerpt_id = *buffer.as_singleton().unwrap().0;
2241            let old_blocks = std::mem::take(&mut self.blocks);
2242            let new_blocks = self
2243                .context
2244                .read(cx)
2245                .messages(cx)
2246                .map(|message| BlockProperties {
2247                    position: buffer
2248                        .anchor_in_excerpt(excerpt_id, message.anchor)
2249                        .unwrap(),
2250                    height: 2,
2251                    style: BlockStyle::Sticky,
2252                    render: Box::new({
2253                        let context = self.context.clone();
2254                        move |cx| {
2255                            let message_id = message.id;
2256                            let sender = ButtonLike::new("role")
2257                                .style(ButtonStyle::Filled)
2258                                .child(match message.role {
2259                                    Role::User => Label::new("You").color(Color::Default),
2260                                    Role::Assistant => Label::new("Assistant").color(Color::Info),
2261                                    Role::System => Label::new("System").color(Color::Warning),
2262                                })
2263                                .tooltip(|cx| {
2264                                    Tooltip::with_meta(
2265                                        "Toggle message role",
2266                                        None,
2267                                        "Available roles: You (User), Assistant, System",
2268                                        cx,
2269                                    )
2270                                })
2271                                .on_click({
2272                                    let context = context.clone();
2273                                    move |_, cx| {
2274                                        context.update(cx, |context, cx| {
2275                                            context.cycle_message_roles(
2276                                                HashSet::from_iter(Some(message_id)),
2277                                                cx,
2278                                            )
2279                                        })
2280                                    }
2281                                });
2282
2283                            let trigger = Button::new("show-error", "Error")
2284                                .color(Color::Error)
2285                                .selected_label_color(Color::Error)
2286                                .selected_icon_color(Color::Error)
2287                                .icon(IconName::XCircle)
2288                                .icon_color(Color::Error)
2289                                .icon_size(IconSize::Small)
2290                                .icon_position(IconPosition::Start)
2291                                .tooltip(move |cx| {
2292                                    Tooltip::with_meta(
2293                                        "Error interacting with language model",
2294                                        None,
2295                                        "Click for more details",
2296                                        cx,
2297                                    )
2298                                });
2299                            h_flex()
2300                                .id(("message_header", message_id.as_u64()))
2301                                .pl(cx.gutter_dimensions.full_width())
2302                                .h_11()
2303                                .w_full()
2304                                .relative()
2305                                .gap_1()
2306                                .child(sender)
2307                                .children(
2308                                    if let MessageStatus::Error(error) = message.status.clone() {
2309                                        Some(
2310                                            PopoverMenu::new("show-error-popover")
2311                                                .menu(move |cx| {
2312                                                    Some(cx.new_view(|cx| ErrorPopover {
2313                                                        error: error.clone(),
2314                                                        focus_handle: cx.focus_handle(),
2315                                                    }))
2316                                                })
2317                                                .trigger(trigger),
2318                                        )
2319                                    } else {
2320                                        None
2321                                    },
2322                                )
2323                                .into_any_element()
2324                        }
2325                    }),
2326                    disposition: BlockDisposition::Above,
2327                })
2328                .collect::<Vec<_>>();
2329
2330            editor.remove_blocks(old_blocks, None, cx);
2331            let ids = editor.insert_blocks(new_blocks, None, cx);
2332            self.blocks = HashSet::from_iter(ids);
2333        });
2334    }
2335
2336    fn insert_selection(
2337        workspace: &mut Workspace,
2338        _: &InsertIntoEditor,
2339        cx: &mut ViewContext<Workspace>,
2340    ) {
2341        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2342            return;
2343        };
2344        let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2345            return;
2346        };
2347        let Some(active_editor_view) = workspace
2348            .active_item(cx)
2349            .and_then(|item| item.act_as::<Editor>(cx))
2350        else {
2351            return;
2352        };
2353
2354        let context_editor = context_editor_view.read(cx).editor.read(cx);
2355        let anchor = context_editor.selections.newest_anchor();
2356        let text = context_editor
2357            .buffer()
2358            .read(cx)
2359            .read(cx)
2360            .text_for_range(anchor.range())
2361            .collect::<String>();
2362
2363        // If nothing is selected, don't delete the current selection; instead, be a no-op.
2364        if !text.is_empty() {
2365            active_editor_view.update(cx, |editor, cx| {
2366                editor.insert(&text, cx);
2367                editor.focus(cx);
2368            })
2369        }
2370    }
2371
2372    fn quote_selection(
2373        workspace: &mut Workspace,
2374        _: &QuoteSelection,
2375        cx: &mut ViewContext<Workspace>,
2376    ) {
2377        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2378            return;
2379        };
2380        let Some(editor) = workspace
2381            .active_item(cx)
2382            .and_then(|item| item.act_as::<Editor>(cx))
2383        else {
2384            return;
2385        };
2386
2387        let selection = editor.update(cx, |editor, cx| editor.selections.newest_adjusted(cx));
2388        let editor = editor.read(cx);
2389        let buffer = editor.buffer().read(cx).snapshot(cx);
2390        let range = editor::ToOffset::to_offset(&selection.start, &buffer)
2391            ..editor::ToOffset::to_offset(&selection.end, &buffer);
2392        let start_language = buffer.language_at(range.start);
2393        let end_language = buffer.language_at(range.end);
2394        let language_name = if start_language == end_language {
2395            start_language.map(|language| language.code_fence_block_name())
2396        } else {
2397            None
2398        };
2399        let language_name = language_name.as_deref().unwrap_or("");
2400
2401        let selected_text = buffer.text_for_range(range).collect::<String>();
2402        let text = if selected_text.is_empty() {
2403            None
2404        } else {
2405            Some(if language_name == "markdown" {
2406                selected_text
2407                    .lines()
2408                    .map(|line| format!("> {}", line))
2409                    .collect::<Vec<_>>()
2410                    .join("\n")
2411            } else {
2412                format!("```{language_name}\n{selected_text}\n```")
2413            })
2414        };
2415
2416        // Activate the panel
2417        if !panel.focus_handle(cx).contains_focused(cx) {
2418            workspace.toggle_panel_focus::<AssistantPanel>(cx);
2419        }
2420
2421        if let Some(text) = text {
2422            panel.update(cx, |_, cx| {
2423                // Wait to create a new context until the workspace is no longer
2424                // being updated.
2425                cx.defer(move |panel, cx| {
2426                    if let Some(context) = panel
2427                        .active_context_editor(cx)
2428                        .or_else(|| panel.new_context(cx))
2429                    {
2430                        context.update(cx, |context, cx| {
2431                            context
2432                                .editor
2433                                .update(cx, |editor, cx| editor.insert(&text, cx))
2434                        });
2435                    };
2436                });
2437            });
2438        }
2439    }
2440
2441    fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
2442        let editor = self.editor.read(cx);
2443        let context = self.context.read(cx);
2444        if editor.selections.count() == 1 {
2445            let selection = editor.selections.newest::<usize>(cx);
2446            let mut copied_text = String::new();
2447            let mut spanned_messages = 0;
2448            for message in context.messages(cx) {
2449                if message.offset_range.start >= selection.range().end {
2450                    break;
2451                } else if message.offset_range.end >= selection.range().start {
2452                    let range = cmp::max(message.offset_range.start, selection.range().start)
2453                        ..cmp::min(message.offset_range.end, selection.range().end);
2454                    if !range.is_empty() {
2455                        spanned_messages += 1;
2456                        write!(&mut copied_text, "## {}\n\n", message.role).unwrap();
2457                        for chunk in context.buffer().read(cx).text_for_range(range) {
2458                            copied_text.push_str(chunk);
2459                        }
2460                        copied_text.push('\n');
2461                    }
2462                }
2463            }
2464
2465            if spanned_messages > 1 {
2466                cx.write_to_clipboard(ClipboardItem::new(copied_text));
2467                return;
2468            }
2469        }
2470
2471        cx.propagate();
2472    }
2473
2474    fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
2475        self.context.update(cx, |context, cx| {
2476            let selections = self.editor.read(cx).selections.disjoint_anchors();
2477            for selection in selections.as_ref() {
2478                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2479                let range = selection
2480                    .map(|endpoint| endpoint.to_offset(&buffer))
2481                    .range();
2482                context.split_message(range, cx);
2483            }
2484        });
2485    }
2486
2487    fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
2488        self.context.update(cx, |context, cx| {
2489            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
2490        });
2491    }
2492
2493    fn title(&self, cx: &AppContext) -> Cow<str> {
2494        self.context
2495            .read(cx)
2496            .summary()
2497            .map(|summary| summary.text.clone())
2498            .map(Cow::Owned)
2499            .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
2500    }
2501
2502    fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
2503        use feature_flags::FeatureFlagAppExt;
2504        let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
2505            assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
2506        });
2507
2508        if nudge.map_or(false, |value| value) {
2509            Some(
2510                h_flex()
2511                    .p_3()
2512                    .border_b_1()
2513                    .border_color(cx.theme().colors().border_variant)
2514                    .bg(cx.theme().colors().editor_background)
2515                    .justify_between()
2516                    .child(
2517                        h_flex()
2518                            .gap_3()
2519                            .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
2520                            .child(Label::new("Zed AI is here! Get started by signing in →")),
2521                    )
2522                    .child(
2523                        Button::new("sign-in", "Sign in")
2524                            .size(ButtonSize::Compact)
2525                            .style(ButtonStyle::Filled)
2526                            .on_click(cx.listener(|this, _event, cx| {
2527                                let client = this
2528                                    .workspace
2529                                    .update(cx, |workspace, _| workspace.client().clone())
2530                                    .log_err();
2531
2532                                if let Some(client) = client {
2533                                    cx.spawn(|this, mut cx| async move {
2534                                        client.authenticate_and_connect(true, &mut cx).await?;
2535                                        this.update(&mut cx, |_, cx| cx.notify())
2536                                    })
2537                                    .detach_and_log_err(cx)
2538                                }
2539                            })),
2540                    )
2541                    .into_any_element(),
2542            )
2543        } else if let Some(configuration_error) = configuration_error(cx) {
2544            let label = match configuration_error {
2545                ConfigurationError::NoProvider => "No LLM provider selected.",
2546                ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
2547            };
2548            Some(
2549                h_flex()
2550                    .p_3()
2551                    .border_b_1()
2552                    .border_color(cx.theme().colors().border_variant)
2553                    .bg(cx.theme().colors().editor_background)
2554                    .justify_between()
2555                    .child(
2556                        h_flex()
2557                            .gap_3()
2558                            .child(
2559                                Icon::new(IconName::ExclamationTriangle)
2560                                    .size(IconSize::Small)
2561                                    .color(Color::Warning),
2562                            )
2563                            .child(Label::new(label)),
2564                    )
2565                    .child(
2566                        Button::new("open-configuration", "Open configuration")
2567                            .size(ButtonSize::Compact)
2568                            .icon_size(IconSize::Small)
2569                            .style(ButtonStyle::Filled)
2570                            .on_click({
2571                                let focus_handle = self.focus_handle(cx).clone();
2572                                move |_event, cx| {
2573                                    focus_handle.dispatch_action(&ShowConfiguration, cx);
2574                                }
2575                            }),
2576                    )
2577                    .into_any_element(),
2578            )
2579        } else {
2580            None
2581        }
2582    }
2583
2584    fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2585        let focus_handle = self.focus_handle(cx).clone();
2586        let button_text = match self.active_workflow_step(cx) {
2587            Some(step) => {
2588                if step.status.is_resolved() {
2589                    "Apply Changes"
2590                } else {
2591                    "Computing Changes..."
2592                }
2593            }
2594            None => "Send",
2595        };
2596
2597        let (style, tooltip) = match token_state(&self.context, cx) {
2598            Some(TokenState::NoTokensLeft { .. }) => (
2599                ButtonStyle::Tinted(TintColor::Negative),
2600                Some(Tooltip::text("Token limit reached", cx)),
2601            ),
2602            Some(TokenState::HasMoreTokens {
2603                over_warn_threshold,
2604                ..
2605            }) => {
2606                let (style, tooltip) = if over_warn_threshold {
2607                    (
2608                        ButtonStyle::Tinted(TintColor::Warning),
2609                        Some(Tooltip::text("Token limit is close to exhaustion", cx)),
2610                    )
2611                } else {
2612                    (ButtonStyle::Filled, None)
2613                };
2614                (style, tooltip)
2615            }
2616            None => (ButtonStyle::Filled, None),
2617        };
2618
2619        ButtonLike::new("send_button")
2620            .style(style)
2621            .when_some(tooltip, |button, tooltip| {
2622                button.tooltip(move |_| tooltip.clone())
2623            })
2624            .layer(ElevationIndex::ModalSurface)
2625            .children(
2626                KeyBinding::for_action_in(&Assist, &focus_handle, cx)
2627                    .map(|binding| binding.into_any_element()),
2628            )
2629            .child(Label::new(button_text))
2630            .on_click(move |_event, cx| {
2631                focus_handle.dispatch_action(&Assist, cx);
2632            })
2633    }
2634
2635    fn workflow_step_range_for_cursor(&self, cx: &AppContext) -> Option<Range<language::Anchor>> {
2636        let newest_cursor = self
2637            .editor
2638            .read(cx)
2639            .selections
2640            .newest_anchor()
2641            .head()
2642            .text_anchor;
2643        let context = self.context.read(cx);
2644        let buffer = context.buffer().read(cx);
2645
2646        let edit_steps = context.workflow_steps();
2647        edit_steps
2648            .binary_search_by(|step| {
2649                let step_range = step.tagged_range.clone();
2650                if newest_cursor.cmp(&step_range.start, buffer).is_lt() {
2651                    Ordering::Greater
2652                } else if newest_cursor.cmp(&step_range.end, buffer).is_gt() {
2653                    Ordering::Less
2654                } else {
2655                    Ordering::Equal
2656                }
2657            })
2658            .ok()
2659            .map(|index| edit_steps[index].tagged_range.clone())
2660    }
2661}
2662
2663impl EventEmitter<EditorEvent> for ContextEditor {}
2664impl EventEmitter<SearchEvent> for ContextEditor {}
2665
2666impl Render for ContextEditor {
2667    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2668        v_flex()
2669            .key_context("ContextEditor")
2670            .capture_action(cx.listener(ContextEditor::cancel_last_assist))
2671            .capture_action(cx.listener(ContextEditor::save))
2672            .capture_action(cx.listener(ContextEditor::copy))
2673            .capture_action(cx.listener(ContextEditor::cycle_message_role))
2674            .capture_action(cx.listener(ContextEditor::confirm_command))
2675            .on_action(cx.listener(ContextEditor::assist))
2676            .on_action(cx.listener(ContextEditor::split))
2677            .on_action(cx.listener(ContextEditor::debug_edit_steps))
2678            .size_full()
2679            .children(self.render_notice(cx))
2680            .child(
2681                div()
2682                    .flex_grow()
2683                    .bg(cx.theme().colors().editor_background)
2684                    .child(self.editor.clone()),
2685            )
2686            .child(
2687                h_flex().flex_none().relative().child(
2688                    h_flex()
2689                        .w_full()
2690                        .absolute()
2691                        .right_4()
2692                        .bottom_2()
2693                        .justify_end()
2694                        .child(self.render_send_button(cx)),
2695                ),
2696            )
2697    }
2698}
2699
2700struct ErrorPopover {
2701    error: SharedString,
2702    focus_handle: FocusHandle,
2703}
2704
2705impl EventEmitter<DismissEvent> for ErrorPopover {}
2706
2707impl FocusableView for ErrorPopover {
2708    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
2709        self.focus_handle.clone()
2710    }
2711}
2712
2713impl Render for ErrorPopover {
2714    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2715        v_flex()
2716            .mt_2()
2717            .max_w_96()
2718            .py_2()
2719            .px_3()
2720            .gap_0p5()
2721            .elevation_2(cx)
2722            .bg(cx.theme().colors().surface_background)
2723            .occlude()
2724            .child(Label::new("Error interacting with language model").weight(FontWeight::SEMIBOLD))
2725            .child(Label::new(self.error.clone()))
2726            .child(
2727                h_flex().justify_end().mt_1().child(
2728                    Button::new("dismiss", "Dismiss")
2729                        .on_click(cx.listener(|_, _, cx| cx.emit(DismissEvent))),
2730                ),
2731            )
2732    }
2733}
2734
2735impl FocusableView for ContextEditor {
2736    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
2737        self.editor.focus_handle(cx)
2738    }
2739}
2740
2741impl Item for ContextEditor {
2742    type Event = editor::EditorEvent;
2743
2744    fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
2745        Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
2746    }
2747
2748    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2749        match event {
2750            EditorEvent::Edited { .. } => {
2751                f(item::ItemEvent::Edit);
2752            }
2753            EditorEvent::TitleChanged => {
2754                f(item::ItemEvent::UpdateTab);
2755            }
2756            _ => {}
2757        }
2758    }
2759
2760    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
2761        Some(self.title(cx).to_string().into())
2762    }
2763
2764    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2765        Some(Box::new(handle.clone()))
2766    }
2767
2768    fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
2769        self.editor.update(cx, |editor, cx| {
2770            Item::set_nav_history(editor, nav_history, cx)
2771        })
2772    }
2773
2774    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
2775        self.editor
2776            .update(cx, |editor, cx| Item::navigate(editor, data, cx))
2777    }
2778
2779    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
2780        self.editor
2781            .update(cx, |editor, cx| Item::deactivated(editor, cx))
2782    }
2783}
2784
2785impl SearchableItem for ContextEditor {
2786    type Match = <Editor as SearchableItem>::Match;
2787
2788    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
2789        self.editor.update(cx, |editor, cx| {
2790            editor.clear_matches(cx);
2791        });
2792    }
2793
2794    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
2795        self.editor
2796            .update(cx, |editor, cx| editor.update_matches(matches, cx));
2797    }
2798
2799    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
2800        self.editor
2801            .update(cx, |editor, cx| editor.query_suggestion(cx))
2802    }
2803
2804    fn activate_match(
2805        &mut self,
2806        index: usize,
2807        matches: &[Self::Match],
2808        cx: &mut ViewContext<Self>,
2809    ) {
2810        self.editor.update(cx, |editor, cx| {
2811            editor.activate_match(index, matches, cx);
2812        });
2813    }
2814
2815    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
2816        self.editor
2817            .update(cx, |editor, cx| editor.select_matches(matches, cx));
2818    }
2819
2820    fn replace(
2821        &mut self,
2822        identifier: &Self::Match,
2823        query: &project::search::SearchQuery,
2824        cx: &mut ViewContext<Self>,
2825    ) {
2826        self.editor
2827            .update(cx, |editor, cx| editor.replace(identifier, query, cx));
2828    }
2829
2830    fn find_matches(
2831        &mut self,
2832        query: Arc<project::search::SearchQuery>,
2833        cx: &mut ViewContext<Self>,
2834    ) -> Task<Vec<Self::Match>> {
2835        self.editor
2836            .update(cx, |editor, cx| editor.find_matches(query, cx))
2837    }
2838
2839    fn active_match_index(
2840        &mut self,
2841        matches: &[Self::Match],
2842        cx: &mut ViewContext<Self>,
2843    ) -> Option<usize> {
2844        self.editor
2845            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
2846    }
2847}
2848
2849impl FollowableItem for ContextEditor {
2850    fn remote_id(&self) -> Option<workspace::ViewId> {
2851        self.remote_id
2852    }
2853
2854    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
2855        let context = self.context.read(cx);
2856        Some(proto::view::Variant::ContextEditor(
2857            proto::view::ContextEditor {
2858                context_id: context.id().to_proto(),
2859                editor: if let Some(proto::view::Variant::Editor(proto)) =
2860                    self.editor.read(cx).to_state_proto(cx)
2861                {
2862                    Some(proto)
2863                } else {
2864                    None
2865                },
2866            },
2867        ))
2868    }
2869
2870    fn from_state_proto(
2871        workspace: View<Workspace>,
2872        id: workspace::ViewId,
2873        state: &mut Option<proto::view::Variant>,
2874        cx: &mut WindowContext,
2875    ) -> Option<Task<Result<View<Self>>>> {
2876        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
2877            return None;
2878        };
2879        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
2880            unreachable!()
2881        };
2882
2883        let context_id = ContextId::from_proto(state.context_id);
2884        let editor_state = state.editor?;
2885
2886        let (project, panel) = workspace.update(cx, |workspace, cx| {
2887            Some((
2888                workspace.project().clone(),
2889                workspace.panel::<AssistantPanel>(cx)?,
2890            ))
2891        })?;
2892
2893        let context_editor =
2894            panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
2895
2896        Some(cx.spawn(|mut cx| async move {
2897            let context_editor = context_editor.await?;
2898            context_editor
2899                .update(&mut cx, |context_editor, cx| {
2900                    context_editor.remote_id = Some(id);
2901                    context_editor.editor.update(cx, |editor, cx| {
2902                        editor.apply_update_proto(
2903                            &project,
2904                            proto::update_view::Variant::Editor(proto::update_view::Editor {
2905                                selections: editor_state.selections,
2906                                pending_selection: editor_state.pending_selection,
2907                                scroll_top_anchor: editor_state.scroll_top_anchor,
2908                                scroll_x: editor_state.scroll_y,
2909                                scroll_y: editor_state.scroll_y,
2910                                ..Default::default()
2911                            }),
2912                            cx,
2913                        )
2914                    })
2915                })?
2916                .await?;
2917            Ok(context_editor)
2918        }))
2919    }
2920
2921    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
2922        Editor::to_follow_event(event)
2923    }
2924
2925    fn add_event_to_update_proto(
2926        &self,
2927        event: &Self::Event,
2928        update: &mut Option<proto::update_view::Variant>,
2929        cx: &WindowContext,
2930    ) -> bool {
2931        self.editor
2932            .read(cx)
2933            .add_event_to_update_proto(event, update, cx)
2934    }
2935
2936    fn apply_update_proto(
2937        &mut self,
2938        project: &Model<Project>,
2939        message: proto::update_view::Variant,
2940        cx: &mut ViewContext<Self>,
2941    ) -> Task<Result<()>> {
2942        self.editor.update(cx, |editor, cx| {
2943            editor.apply_update_proto(project, message, cx)
2944        })
2945    }
2946
2947    fn is_project_item(&self, _cx: &WindowContext) -> bool {
2948        true
2949    }
2950
2951    fn set_leader_peer_id(
2952        &mut self,
2953        leader_peer_id: Option<proto::PeerId>,
2954        cx: &mut ViewContext<Self>,
2955    ) {
2956        self.editor.update(cx, |editor, cx| {
2957            editor.set_leader_peer_id(leader_peer_id, cx)
2958        })
2959    }
2960
2961    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
2962        if existing.context.read(cx).id() == self.context.read(cx).id() {
2963            Some(item::Dedup::KeepExisting)
2964        } else {
2965            None
2966        }
2967    }
2968}
2969
2970pub struct ContextEditorToolbarItem {
2971    fs: Arc<dyn Fs>,
2972    workspace: WeakView<Workspace>,
2973    active_context_editor: Option<WeakView<ContextEditor>>,
2974    model_summary_editor: View<Editor>,
2975}
2976
2977impl ContextEditorToolbarItem {
2978    pub fn new(
2979        workspace: &Workspace,
2980        _model_selector_menu_handle: PopoverMenuHandle<ContextMenu>,
2981        model_summary_editor: View<Editor>,
2982    ) -> Self {
2983        Self {
2984            fs: workspace.app_state().fs.clone(),
2985            workspace: workspace.weak_handle(),
2986            active_context_editor: None,
2987            model_summary_editor,
2988        }
2989    }
2990
2991    fn render_inject_context_menu(&self, cx: &mut ViewContext<Self>) -> impl Element {
2992        let commands = SlashCommandRegistry::global(cx);
2993        let active_editor_focus_handle = self.workspace.upgrade().and_then(|workspace| {
2994            Some(
2995                workspace
2996                    .read(cx)
2997                    .active_item_as::<Editor>(cx)?
2998                    .focus_handle(cx),
2999            )
3000        });
3001        let active_context_editor = self.active_context_editor.clone();
3002
3003        PopoverMenu::new("inject-context-menu")
3004            .trigger(IconButton::new("trigger", IconName::Quote).tooltip(|cx| {
3005                Tooltip::with_meta("Insert Context", None, "Type / to insert via keyboard", cx)
3006            }))
3007            .menu(move |cx| {
3008                let active_context_editor = active_context_editor.clone()?;
3009                ContextMenu::build(cx, |mut menu, _cx| {
3010                    for command_name in commands.featured_command_names() {
3011                        if let Some(command) = commands.command(&command_name) {
3012                            let menu_text = SharedString::from(Arc::from(command.menu_text()));
3013                            menu = menu.custom_entry(
3014                                {
3015                                    let command_name = command_name.clone();
3016                                    move |_cx| {
3017                                        h_flex()
3018                                            .gap_4()
3019                                            .w_full()
3020                                            .justify_between()
3021                                            .child(Label::new(menu_text.clone()))
3022                                            .child(
3023                                                Label::new(format!("/{command_name}"))
3024                                                    .color(Color::Muted),
3025                                            )
3026                                            .into_any()
3027                                    }
3028                                },
3029                                {
3030                                    let active_context_editor = active_context_editor.clone();
3031                                    move |cx| {
3032                                        active_context_editor
3033                                            .update(cx, |context_editor, cx| {
3034                                                context_editor.insert_command(&command_name, cx)
3035                                            })
3036                                            .ok();
3037                                    }
3038                                },
3039                            )
3040                        }
3041                    }
3042
3043                    if let Some(active_editor_focus_handle) = active_editor_focus_handle.clone() {
3044                        menu = menu
3045                            .context(active_editor_focus_handle)
3046                            .action("Quote Selection", Box::new(QuoteSelection));
3047                    }
3048
3049                    menu
3050                })
3051                .into()
3052            })
3053    }
3054
3055    fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
3056        let context = &self
3057            .active_context_editor
3058            .as_ref()?
3059            .upgrade()?
3060            .read(cx)
3061            .context;
3062        let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
3063            TokenState::NoTokensLeft {
3064                max_token_count,
3065                token_count,
3066            } => (Color::Error, token_count, max_token_count),
3067            TokenState::HasMoreTokens {
3068                max_token_count,
3069                token_count,
3070                over_warn_threshold,
3071            } => {
3072                let color = if over_warn_threshold {
3073                    Color::Warning
3074                } else {
3075                    Color::Muted
3076                };
3077                (color, token_count, max_token_count)
3078            }
3079        };
3080        Some(
3081            h_flex()
3082                .gap_0p5()
3083                .child(
3084                    Label::new(humanize_token_count(token_count))
3085                        .size(LabelSize::Small)
3086                        .color(token_count_color),
3087                )
3088                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
3089                .child(
3090                    Label::new(humanize_token_count(max_token_count))
3091                        .size(LabelSize::Small)
3092                        .color(Color::Muted),
3093                ),
3094        )
3095    }
3096}
3097
3098impl Render for ContextEditorToolbarItem {
3099    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3100        let left_side = h_flex()
3101            .gap_2()
3102            .flex_1()
3103            .min_w(rems(DEFAULT_TAB_TITLE.len() as f32))
3104            .when(self.active_context_editor.is_some(), |left_side| {
3105                left_side
3106                    .child(
3107                        IconButton::new("regenerate-context", IconName::ArrowCircle)
3108                            .visible_on_hover("toolbar")
3109                            .tooltip(|cx| Tooltip::text("Regenerate Summary", cx))
3110                            .on_click(cx.listener(move |_, _, cx| {
3111                                cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3112                            })),
3113                    )
3114                    .child(self.model_summary_editor.clone())
3115            });
3116
3117        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
3118        let active_model = LanguageModelRegistry::read_global(cx).active_model();
3119
3120        let right_side = h_flex()
3121            .gap_2()
3122            .child(ModelSelector::new(
3123                self.fs.clone(),
3124                ButtonLike::new("active-model")
3125                    .style(ButtonStyle::Subtle)
3126                    .child(
3127                        h_flex()
3128                            .w_full()
3129                            .gap_0p5()
3130                            .child(
3131                                div()
3132                                    .overflow_x_hidden()
3133                                    .flex_grow()
3134                                    .whitespace_nowrap()
3135                                    .child(match (active_provider, active_model) {
3136                                        (Some(provider), Some(model)) => h_flex()
3137                                            .gap_1()
3138                                            .child(
3139                                                Icon::new(provider.icon())
3140                                                    .color(Color::Muted)
3141                                                    .size(IconSize::XSmall),
3142                                            )
3143                                            .child(
3144                                                Label::new(model.name().0)
3145                                                    .size(LabelSize::Small)
3146                                                    .color(Color::Muted),
3147                                            )
3148                                            .into_any_element(),
3149                                        _ => Label::new("No model selected")
3150                                            .size(LabelSize::Small)
3151                                            .color(Color::Muted)
3152                                            .into_any_element(),
3153                                    }),
3154                            )
3155                            .child(
3156                                Icon::new(IconName::ChevronDown)
3157                                    .color(Color::Muted)
3158                                    .size(IconSize::XSmall),
3159                            ),
3160                    )
3161                    .tooltip(move |cx| {
3162                        Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
3163                    }),
3164            ))
3165            .children(self.render_remaining_tokens(cx))
3166            .child(self.render_inject_context_menu(cx));
3167
3168        h_flex()
3169            .size_full()
3170            .justify_between()
3171            .child(left_side)
3172            .child(right_side)
3173    }
3174}
3175
3176impl ToolbarItemView for ContextEditorToolbarItem {
3177    fn set_active_pane_item(
3178        &mut self,
3179        active_pane_item: Option<&dyn ItemHandle>,
3180        cx: &mut ViewContext<Self>,
3181    ) -> ToolbarItemLocation {
3182        self.active_context_editor = active_pane_item
3183            .and_then(|item| item.act_as::<ContextEditor>(cx))
3184            .map(|editor| editor.downgrade());
3185        cx.notify();
3186        if self.active_context_editor.is_none() {
3187            ToolbarItemLocation::Hidden
3188        } else {
3189            ToolbarItemLocation::PrimaryRight
3190        }
3191    }
3192
3193    fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
3194        cx.notify();
3195    }
3196}
3197
3198impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
3199
3200enum ContextEditorToolbarItemEvent {
3201    RegenerateSummary,
3202}
3203impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
3204
3205pub struct ContextHistory {
3206    picker: View<Picker<SavedContextPickerDelegate>>,
3207    _subscriptions: Vec<Subscription>,
3208    assistant_panel: WeakView<AssistantPanel>,
3209}
3210
3211impl ContextHistory {
3212    fn new(
3213        project: Model<Project>,
3214        context_store: Model<ContextStore>,
3215        assistant_panel: WeakView<AssistantPanel>,
3216        cx: &mut ViewContext<Self>,
3217    ) -> Self {
3218        let picker = cx.new_view(|cx| {
3219            Picker::uniform_list(
3220                SavedContextPickerDelegate::new(project, context_store.clone()),
3221                cx,
3222            )
3223            .modal(false)
3224            .max_height(None)
3225        });
3226
3227        let _subscriptions = vec![
3228            cx.observe(&context_store, |this, _, cx| {
3229                this.picker.update(cx, |picker, cx| picker.refresh(cx));
3230            }),
3231            cx.subscribe(&picker, Self::handle_picker_event),
3232        ];
3233
3234        Self {
3235            picker,
3236            _subscriptions,
3237            assistant_panel,
3238        }
3239    }
3240
3241    fn handle_picker_event(
3242        &mut self,
3243        _: View<Picker<SavedContextPickerDelegate>>,
3244        event: &SavedContextPickerEvent,
3245        cx: &mut ViewContext<Self>,
3246    ) {
3247        let SavedContextPickerEvent::Confirmed(context) = event;
3248        self.assistant_panel
3249            .update(cx, |assistant_panel, cx| match context {
3250                ContextMetadata::Remote(metadata) => {
3251                    assistant_panel
3252                        .open_remote_context(metadata.id.clone(), cx)
3253                        .detach_and_log_err(cx);
3254                }
3255                ContextMetadata::Saved(metadata) => {
3256                    assistant_panel
3257                        .open_saved_context(metadata.path.clone(), cx)
3258                        .detach_and_log_err(cx);
3259                }
3260            })
3261            .ok();
3262    }
3263}
3264
3265impl Render for ContextHistory {
3266    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
3267        div().size_full().child(self.picker.clone())
3268    }
3269}
3270
3271impl FocusableView for ContextHistory {
3272    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
3273        self.picker.focus_handle(cx)
3274    }
3275}
3276
3277impl EventEmitter<()> for ContextHistory {}
3278
3279impl Item for ContextHistory {
3280    type Event = ();
3281
3282    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
3283        Some("History".into())
3284    }
3285}
3286
3287pub struct ConfigurationView {
3288    focus_handle: FocusHandle,
3289    configuration_views: HashMap<LanguageModelProviderId, AnyView>,
3290    _registry_subscription: Subscription,
3291}
3292
3293impl ConfigurationView {
3294    fn new(cx: &mut ViewContext<Self>) -> Self {
3295        let focus_handle = cx.focus_handle();
3296
3297        let registry_subscription = cx.subscribe(
3298            &LanguageModelRegistry::global(cx),
3299            |this, _, event: &language_model::Event, cx| match event {
3300                language_model::Event::AddedProvider(provider_id) => {
3301                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
3302                    if let Some(provider) = provider {
3303                        this.add_configuration_view(&provider, cx);
3304                    }
3305                }
3306                language_model::Event::RemovedProvider(provider_id) => {
3307                    this.remove_configuration_view(provider_id);
3308                }
3309                _ => {}
3310            },
3311        );
3312
3313        let mut this = Self {
3314            focus_handle,
3315            configuration_views: HashMap::default(),
3316            _registry_subscription: registry_subscription,
3317        };
3318        this.build_configuration_views(cx);
3319        this
3320    }
3321
3322    fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
3323        let providers = LanguageModelRegistry::read_global(cx).providers();
3324        for provider in providers {
3325            self.add_configuration_view(&provider, cx);
3326        }
3327    }
3328
3329    fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
3330        self.configuration_views.remove(provider_id);
3331    }
3332
3333    fn add_configuration_view(
3334        &mut self,
3335        provider: &Arc<dyn LanguageModelProvider>,
3336        cx: &mut ViewContext<Self>,
3337    ) {
3338        let configuration_view = provider.configuration_view(cx);
3339        self.configuration_views
3340            .insert(provider.id(), configuration_view);
3341    }
3342
3343    fn render_provider_view(
3344        &mut self,
3345        provider: &Arc<dyn LanguageModelProvider>,
3346        cx: &mut ViewContext<Self>,
3347    ) -> Div {
3348        let provider_name = provider.name().0.clone();
3349        let configuration_view = self.configuration_views.get(&provider.id()).cloned();
3350
3351        let open_new_context = cx.listener({
3352            let provider = provider.clone();
3353            move |_, _, cx| {
3354                cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
3355                    provider.clone(),
3356                ))
3357            }
3358        });
3359
3360        v_flex()
3361            .gap_2()
3362            .child(
3363                h_flex()
3364                    .justify_between()
3365                    .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
3366                    .when(provider.is_authenticated(cx), move |this| {
3367                        this.child(
3368                            h_flex().justify_end().child(
3369                                Button::new("new-context", "Open new context")
3370                                    .icon_position(IconPosition::Start)
3371                                    .icon(IconName::Plus)
3372                                    .style(ButtonStyle::Filled)
3373                                    .layer(ElevationIndex::ModalSurface)
3374                                    .on_click(open_new_context),
3375                            ),
3376                        )
3377                    }),
3378            )
3379            .child(
3380                div()
3381                    .p(Spacing::Large.rems(cx))
3382                    .bg(cx.theme().colors().surface_background)
3383                    .border_1()
3384                    .border_color(cx.theme().colors().border_variant)
3385                    .rounded_md()
3386                    .when(configuration_view.is_none(), |this| {
3387                        this.child(div().child(Label::new(format!(
3388                            "No configuration view for {}",
3389                            provider_name
3390                        ))))
3391                    })
3392                    .when_some(configuration_view, |this, configuration_view| {
3393                        this.child(configuration_view)
3394                    }),
3395            )
3396    }
3397}
3398
3399impl Render for ConfigurationView {
3400    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3401        let providers = LanguageModelRegistry::read_global(cx).providers();
3402        let provider_views = providers
3403            .into_iter()
3404            .map(|provider| self.render_provider_view(&provider, cx))
3405            .collect::<Vec<_>>();
3406
3407        v_flex()
3408            .id("assistant-configuration-view")
3409            .track_focus(&self.focus_handle)
3410            .bg(cx.theme().colors().editor_background)
3411            .size_full()
3412            .overflow_y_scroll()
3413            .child(
3414                v_flex()
3415                    .p(Spacing::XXLarge.rems(cx))
3416                    .border_b_1()
3417                    .border_color(cx.theme().colors().border)
3418                    .gap_1()
3419                    .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
3420                    .child(
3421                        Label::new(
3422                            "At least one LLM provider must be configured to use the Assistant.",
3423                        )
3424                        .color(Color::Muted),
3425                    ),
3426            )
3427            .child(
3428                v_flex()
3429                    .p(Spacing::XXLarge.rems(cx))
3430                    .mt_1()
3431                    .gap_6()
3432                    .size_full()
3433                    .children(provider_views),
3434            )
3435    }
3436}
3437
3438pub enum ConfigurationViewEvent {
3439    NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
3440}
3441
3442impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
3443
3444impl FocusableView for ConfigurationView {
3445    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
3446        self.focus_handle.clone()
3447    }
3448}
3449
3450impl Item for ConfigurationView {
3451    type Event = ConfigurationViewEvent;
3452
3453    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
3454        Some("Configuration".into())
3455    }
3456}
3457
3458type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
3459
3460fn render_slash_command_output_toggle(
3461    row: MultiBufferRow,
3462    is_folded: bool,
3463    fold: ToggleFold,
3464    _cx: &mut WindowContext,
3465) -> AnyElement {
3466    Disclosure::new(
3467        ("slash-command-output-fold-indicator", row.0 as u64),
3468        !is_folded,
3469    )
3470    .selected(is_folded)
3471    .on_click(move |_e, cx| fold(!is_folded, cx))
3472    .into_any_element()
3473}
3474
3475fn render_pending_slash_command_gutter_decoration(
3476    row: MultiBufferRow,
3477    status: &PendingSlashCommandStatus,
3478    confirm_command: Arc<dyn Fn(&mut WindowContext)>,
3479) -> AnyElement {
3480    let mut icon = IconButton::new(
3481        ("slash-command-gutter-decoration", row.0),
3482        ui::IconName::TriangleRight,
3483    )
3484    .on_click(move |_e, cx| confirm_command(cx))
3485    .icon_size(ui::IconSize::Small)
3486    .size(ui::ButtonSize::None);
3487
3488    match status {
3489        PendingSlashCommandStatus::Idle => {
3490            icon = icon.icon_color(Color::Muted);
3491        }
3492        PendingSlashCommandStatus::Running { .. } => {
3493            icon = icon.selected(true);
3494        }
3495        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
3496    }
3497
3498    icon.into_any_element()
3499}
3500
3501fn render_docs_slash_command_trailer(
3502    row: MultiBufferRow,
3503    command: PendingSlashCommand,
3504    cx: &mut WindowContext,
3505) -> AnyElement {
3506    let Some(argument) = command.argument else {
3507        return Empty.into_any();
3508    };
3509
3510    let args = DocsSlashCommandArgs::parse(&argument);
3511
3512    let Some(store) = args
3513        .provider()
3514        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
3515    else {
3516        return Empty.into_any();
3517    };
3518
3519    let Some(package) = args.package() else {
3520        return Empty.into_any();
3521    };
3522
3523    let mut children = Vec::new();
3524
3525    if store.is_indexing(&package) {
3526        children.push(
3527            div()
3528                .id(("crates-being-indexed", row.0))
3529                .child(Icon::new(IconName::ArrowCircle).with_animation(
3530                    "arrow-circle",
3531                    Animation::new(Duration::from_secs(4)).repeat(),
3532                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3533                ))
3534                .tooltip({
3535                    let package = package.clone();
3536                    move |cx| Tooltip::text(format!("Indexing {package}"), cx)
3537                })
3538                .into_any_element(),
3539        );
3540    }
3541
3542    if let Some(latest_error) = store.latest_error_for_package(&package) {
3543        children.push(
3544            div()
3545                .id(("latest-error", row.0))
3546                .child(
3547                    Icon::new(IconName::ExclamationTriangle)
3548                        .size(IconSize::Small)
3549                        .color(Color::Warning),
3550                )
3551                .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
3552                .into_any_element(),
3553        )
3554    }
3555
3556    let is_indexing = store.is_indexing(&package);
3557    let latest_error = store.latest_error_for_package(&package);
3558
3559    if !is_indexing && latest_error.is_none() {
3560        return Empty.into_any();
3561    }
3562
3563    h_flex().gap_2().children(children).into_any_element()
3564}
3565
3566fn make_lsp_adapter_delegate(
3567    project: &Model<Project>,
3568    cx: &mut AppContext,
3569) -> Result<Arc<dyn LspAdapterDelegate>> {
3570    project.update(cx, |project, cx| {
3571        // TODO: Find the right worktree.
3572        let worktree = project
3573            .worktrees(cx)
3574            .next()
3575            .ok_or_else(|| anyhow!("no worktrees when constructing ProjectLspAdapterDelegate"))?;
3576        Ok(ProjectLspAdapterDelegate::new(project, &worktree, cx) as Arc<dyn LspAdapterDelegate>)
3577    })
3578}
3579
3580fn slash_command_error_block_renderer(message: String) -> RenderBlock {
3581    Box::new(move |_| {
3582        div()
3583            .pl_6()
3584            .child(
3585                Label::new(format!("error: {}", message))
3586                    .single_line()
3587                    .color(Color::Error),
3588            )
3589            .into_any()
3590    })
3591}
3592
3593enum TokenState {
3594    NoTokensLeft {
3595        max_token_count: usize,
3596        token_count: usize,
3597    },
3598    HasMoreTokens {
3599        max_token_count: usize,
3600        token_count: usize,
3601        over_warn_threshold: bool,
3602    },
3603}
3604
3605fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
3606    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3607
3608    let model = LanguageModelRegistry::read_global(cx).active_model()?;
3609    let token_count = context.read(cx).token_count()?;
3610    let max_token_count = model.max_token_count();
3611
3612    let remaining_tokens = max_token_count as isize - token_count as isize;
3613    let token_state = if remaining_tokens <= 0 {
3614        TokenState::NoTokensLeft {
3615            max_token_count,
3616            token_count,
3617        }
3618    } else {
3619        let over_warn_threshold =
3620            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3621        TokenState::HasMoreTokens {
3622            max_token_count,
3623            token_count,
3624            over_warn_threshold,
3625        }
3626    };
3627    Some(token_state)
3628}
3629
3630enum ConfigurationError {
3631    NoProvider,
3632    ProviderNotAuthenticated,
3633}
3634
3635fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
3636    let provider = LanguageModelRegistry::read_global(cx).active_provider();
3637    let is_authenticated = provider
3638        .as_ref()
3639        .map_or(false, |provider| provider.is_authenticated(cx));
3640
3641    if provider.is_some() && is_authenticated {
3642        return None;
3643    }
3644
3645    if provider.is_none() {
3646        return Some(ConfigurationError::NoProvider);
3647    }
3648
3649    if !is_authenticated {
3650        return Some(ConfigurationError::ProviderNotAuthenticated);
3651    }
3652
3653    None
3654}