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