assistant_panel.rs

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