assistant_panel.rs

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