assistant_panel.rs

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