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                    text.push('\n');
3537                }
3538            }
3539        }
3540
3541        (text, CopyMetadata { creases })
3542    }
3543
3544    fn paste(&mut self, action: &editor::actions::Paste, cx: &mut ViewContext<Self>) {
3545        cx.stop_propagation();
3546
3547        let images = if let Some(item) = cx.read_from_clipboard() {
3548            item.into_entries()
3549                .filter_map(|entry| {
3550                    if let ClipboardEntry::Image(image) = entry {
3551                        Some(image)
3552                    } else {
3553                        None
3554                    }
3555                })
3556                .collect()
3557        } else {
3558            Vec::new()
3559        };
3560
3561        let metadata = if let Some(item) = cx.read_from_clipboard() {
3562            item.entries().first().and_then(|entry| {
3563                if let ClipboardEntry::String(text) = entry {
3564                    text.metadata_json::<CopyMetadata>()
3565                } else {
3566                    None
3567                }
3568            })
3569        } else {
3570            None
3571        };
3572
3573        if images.is_empty() {
3574            self.editor.update(cx, |editor, cx| {
3575                let paste_position = editor.selections.newest::<usize>(cx).head();
3576                editor.paste(action, cx);
3577
3578                if let Some(metadata) = metadata {
3579                    let buffer = editor.buffer().read(cx).snapshot(cx);
3580
3581                    let mut buffer_rows_to_fold = BTreeSet::new();
3582                    let weak_editor = cx.view().downgrade();
3583                    editor.insert_creases(
3584                        metadata.creases.into_iter().map(|metadata| {
3585                            let start = buffer.anchor_after(
3586                                paste_position + metadata.range_relative_to_selection.start,
3587                            );
3588                            let end = buffer.anchor_before(
3589                                paste_position + metadata.range_relative_to_selection.end,
3590                            );
3591
3592                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
3593                            buffer_rows_to_fold.insert(buffer_row);
3594                            Crease::new(
3595                                start..end,
3596                                FoldPlaceholder {
3597                                    constrain_width: false,
3598                                    render: render_fold_icon_button(
3599                                        weak_editor.clone(),
3600                                        metadata.crease.icon,
3601                                        metadata.crease.label.clone(),
3602                                    ),
3603                                    merge_adjacent: false,
3604                                },
3605                                render_slash_command_output_toggle,
3606                                |_, _, _| Empty.into_any(),
3607                            )
3608                            .with_metadata(metadata.crease.clone())
3609                        }),
3610                        cx,
3611                    );
3612                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
3613                        editor.fold_at(&FoldAt { buffer_row }, cx);
3614                    }
3615                }
3616            });
3617        } else {
3618            let mut image_positions = Vec::new();
3619            self.editor.update(cx, |editor, cx| {
3620                editor.transact(cx, |editor, cx| {
3621                    let edits = editor
3622                        .selections
3623                        .all::<usize>(cx)
3624                        .into_iter()
3625                        .map(|selection| (selection.start..selection.end, "\n"));
3626                    editor.edit(edits, cx);
3627
3628                    let snapshot = editor.buffer().read(cx).snapshot(cx);
3629                    for selection in editor.selections.all::<usize>(cx) {
3630                        image_positions.push(snapshot.anchor_before(selection.end));
3631                    }
3632                });
3633            });
3634
3635            self.context.update(cx, |context, cx| {
3636                for image in images {
3637                    let Some(render_image) = image.to_image_data(cx).log_err() else {
3638                        continue;
3639                    };
3640                    let image_id = image.id();
3641                    let image_task = LanguageModelImage::from_image(image, cx).shared();
3642
3643                    for image_position in image_positions.iter() {
3644                        context.insert_content(
3645                            Content::Image {
3646                                anchor: image_position.text_anchor,
3647                                image_id,
3648                                image: image_task.clone(),
3649                                render_image: render_image.clone(),
3650                            },
3651                            cx,
3652                        );
3653                    }
3654                }
3655            });
3656        }
3657    }
3658
3659    fn update_image_blocks(&mut self, cx: &mut ViewContext<Self>) {
3660        self.editor.update(cx, |editor, cx| {
3661            let buffer = editor.buffer().read(cx).snapshot(cx);
3662            let excerpt_id = *buffer.as_singleton().unwrap().0;
3663            let old_blocks = std::mem::take(&mut self.image_blocks);
3664            let new_blocks = self
3665                .context
3666                .read(cx)
3667                .contents(cx)
3668                .filter_map(|content| {
3669                    if let Content::Image {
3670                        anchor,
3671                        render_image,
3672                        ..
3673                    } = content
3674                    {
3675                        Some((anchor, render_image))
3676                    } else {
3677                        None
3678                    }
3679                })
3680                .filter_map(|(anchor, render_image)| {
3681                    const MAX_HEIGHT_IN_LINES: u32 = 8;
3682                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
3683                    let image = render_image.clone();
3684                    anchor.is_valid(&buffer).then(|| BlockProperties {
3685                        position: anchor,
3686                        height: MAX_HEIGHT_IN_LINES,
3687                        style: BlockStyle::Sticky,
3688                        render: Box::new(move |cx| {
3689                            let image_size = size_for_image(
3690                                &image,
3691                                size(
3692                                    cx.max_width - cx.gutter_dimensions.full_width(),
3693                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
3694                                ),
3695                            );
3696                            h_flex()
3697                                .pl(cx.gutter_dimensions.full_width())
3698                                .child(
3699                                    img(image.clone())
3700                                        .object_fit(gpui::ObjectFit::ScaleDown)
3701                                        .w(image_size.width)
3702                                        .h(image_size.height),
3703                                )
3704                                .into_any_element()
3705                        }),
3706
3707                        disposition: BlockDisposition::Above,
3708                        priority: 0,
3709                    })
3710                })
3711                .collect::<Vec<_>>();
3712
3713            editor.remove_blocks(old_blocks, None, cx);
3714            let ids = editor.insert_blocks(new_blocks, None, cx);
3715            self.image_blocks = HashSet::from_iter(ids);
3716        });
3717    }
3718
3719    fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
3720        self.context.update(cx, |context, cx| {
3721            let selections = self.editor.read(cx).selections.disjoint_anchors();
3722            for selection in selections.as_ref() {
3723                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
3724                let range = selection
3725                    .map(|endpoint| endpoint.to_offset(&buffer))
3726                    .range();
3727                context.split_message(range, cx);
3728            }
3729        });
3730    }
3731
3732    fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
3733        self.context.update(cx, |context, cx| {
3734            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
3735        });
3736    }
3737
3738    fn title(&self, cx: &AppContext) -> Cow<str> {
3739        self.context
3740            .read(cx)
3741            .summary()
3742            .map(|summary| summary.text.clone())
3743            .map(Cow::Owned)
3744            .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
3745    }
3746
3747    fn render_workflow_step_header(
3748        &self,
3749        range: Range<text::Anchor>,
3750        max_width: Pixels,
3751        gutter_width: Pixels,
3752        id: BlockId,
3753        cx: &mut ViewContext<Self>,
3754    ) -> Option<AnyElement> {
3755        let step_state = self.workflow_steps.get(&range)?;
3756        let status = step_state.status(cx);
3757        let this = cx.view().downgrade();
3758
3759        let theme = cx.theme().status();
3760        let is_confirmed = status.is_confirmed();
3761        let border_color = if is_confirmed {
3762            theme.ignored_border
3763        } else {
3764            theme.info_border
3765        };
3766
3767        let editor = self.editor.read(cx);
3768        let focus_handle = editor.focus_handle(cx);
3769        let snapshot = editor
3770            .buffer()
3771            .read(cx)
3772            .as_singleton()?
3773            .read(cx)
3774            .text_snapshot();
3775        let start_offset = range.start.to_offset(&snapshot);
3776        let parent_message = self
3777            .context
3778            .read(cx)
3779            .messages_for_offsets([start_offset], cx);
3780        debug_assert_eq!(parent_message.len(), 1);
3781        let parent_message = parent_message.first()?;
3782
3783        let step_index = self
3784            .workflow_steps
3785            .keys()
3786            .filter(|workflow_step_range| {
3787                workflow_step_range
3788                    .start
3789                    .cmp(&parent_message.anchor_range.start, &snapshot)
3790                    .is_ge()
3791                    && workflow_step_range.end.cmp(&range.end, &snapshot).is_le()
3792            })
3793            .count();
3794
3795        let step_label = Label::new(format!("Step {step_index}")).size(LabelSize::Small);
3796
3797        let step_label = if is_confirmed {
3798            h_flex()
3799                .items_center()
3800                .gap_2()
3801                .child(step_label.strikethrough(true).color(Color::Muted))
3802                .child(
3803                    Icon::new(IconName::Check)
3804                        .size(IconSize::Small)
3805                        .color(Color::Created),
3806                )
3807        } else {
3808            div().child(step_label)
3809        };
3810
3811        Some(
3812            v_flex()
3813                .w(max_width)
3814                .pl(gutter_width)
3815                .child(
3816                    h_flex()
3817                        .w_full()
3818                        .h_8()
3819                        .border_b_1()
3820                        .border_color(border_color)
3821                        .items_center()
3822                        .justify_between()
3823                        .gap_2()
3824                        .child(h_flex().justify_start().gap_2().child(step_label))
3825                        .child(h_flex().w_full().justify_end().child(
3826                            Self::render_workflow_step_status(
3827                                status,
3828                                range.clone(),
3829                                focus_handle.clone(),
3830                                this.clone(),
3831                                id,
3832                            ),
3833                        )),
3834                )
3835                // todo!("do we wanna keep this?")
3836                // .children(edit_paths.iter().map(|path| {
3837                //     h_flex()
3838                //         .gap_1()
3839                //         .child(Icon::new(IconName::File))
3840                //         .child(Label::new(path.clone()))
3841                // }))
3842                .into_any(),
3843        )
3844    }
3845
3846    fn render_workflow_step_footer(
3847        &self,
3848        step_range: Range<text::Anchor>,
3849        max_width: Pixels,
3850        gutter_width: Pixels,
3851        cx: &mut ViewContext<Self>,
3852    ) -> Option<AnyElement> {
3853        let step = self.workflow_steps.get(&step_range)?;
3854        let current_status = step.status(cx);
3855        let theme = cx.theme().status();
3856        let border_color = if current_status.is_confirmed() {
3857            theme.ignored_border
3858        } else {
3859            theme.info_border
3860        };
3861        Some(
3862            v_flex()
3863                .w(max_width)
3864                .pt_1()
3865                .pl(gutter_width)
3866                .child(h_flex().h(px(1.)).bg(border_color))
3867                .into_any(),
3868        )
3869    }
3870
3871    fn render_workflow_step_status(
3872        status: WorkflowStepStatus,
3873        step_range: Range<language::Anchor>,
3874        focus_handle: FocusHandle,
3875        editor: WeakView<ContextEditor>,
3876        id: BlockId,
3877    ) -> AnyElement {
3878        let id = EntityId::from(id).as_u64();
3879        fn display_keybind_in_tooltip(
3880            step_range: &Range<language::Anchor>,
3881            editor: &WeakView<ContextEditor>,
3882            cx: &mut WindowContext<'_>,
3883        ) -> bool {
3884            editor
3885                .update(cx, |this, _| {
3886                    this.active_workflow_step
3887                        .as_ref()
3888                        .map(|step| &step.range == step_range)
3889                })
3890                .ok()
3891                .flatten()
3892                .unwrap_or_default()
3893        }
3894
3895        match status {
3896            WorkflowStepStatus::Error(error) => {
3897                let error = error.to_string();
3898                h_flex()
3899                    .gap_2()
3900                    .child(
3901                        div()
3902                            .id("step-resolution-failure")
3903                            .child(
3904                                Label::new("Step Resolution Failed")
3905                                    .size(LabelSize::Small)
3906                                    .color(Color::Error),
3907                            )
3908                            .tooltip(move |cx| Tooltip::text(error.clone(), cx)),
3909                    )
3910                    .child(
3911                        Button::new(("transform", id), "Retry")
3912                            .icon(IconName::Update)
3913                            .icon_position(IconPosition::Start)
3914                            .icon_size(IconSize::Small)
3915                            .label_size(LabelSize::Small)
3916                            .on_click({
3917                                let editor = editor.clone();
3918                                let step_range = step_range.clone();
3919                                move |_, cx| {
3920                                    editor
3921                                        .update(cx, |this, cx| {
3922                                            this.resolve_workflow_step(step_range.clone(), cx)
3923                                        })
3924                                        .ok();
3925                                }
3926                            }),
3927                    )
3928                    .into_any()
3929            }
3930            WorkflowStepStatus::Idle | WorkflowStepStatus::Resolving { .. } => {
3931                Button::new(("transform", id), "Transform")
3932                    .icon(IconName::SparkleAlt)
3933                    .icon_position(IconPosition::Start)
3934                    .icon_size(IconSize::Small)
3935                    .label_size(LabelSize::Small)
3936                    .style(ButtonStyle::Tinted(TintColor::Accent))
3937                    .tooltip({
3938                        let step_range = step_range.clone();
3939                        let editor = editor.clone();
3940                        move |cx| {
3941                            cx.new_view(|cx| {
3942                                let tooltip = Tooltip::new("Transform");
3943                                if display_keybind_in_tooltip(&step_range, &editor, cx) {
3944                                    tooltip.key_binding(KeyBinding::for_action_in(
3945                                        &Assist,
3946                                        &focus_handle,
3947                                        cx,
3948                                    ))
3949                                } else {
3950                                    tooltip
3951                                }
3952                            })
3953                            .into()
3954                        }
3955                    })
3956                    .on_click({
3957                        let editor = editor.clone();
3958                        let step_range = step_range.clone();
3959                        let is_idle = matches!(status, WorkflowStepStatus::Idle);
3960                        move |_, cx| {
3961                            if is_idle {
3962                                editor
3963                                    .update(cx, |this, cx| {
3964                                        this.apply_workflow_step(step_range.clone(), cx)
3965                                    })
3966                                    .ok();
3967                            }
3968                        }
3969                    })
3970                    .map(|this| {
3971                        if let WorkflowStepStatus::Resolving = &status {
3972                            this.with_animation(
3973                                ("resolving-suggestion-animation", id),
3974                                Animation::new(Duration::from_secs(2))
3975                                    .repeat()
3976                                    .with_easing(pulsating_between(0.4, 0.8)),
3977                                |label, delta| label.alpha(delta),
3978                            )
3979                            .into_any_element()
3980                        } else {
3981                            this.into_any_element()
3982                        }
3983                    })
3984            }
3985            WorkflowStepStatus::Pending => h_flex()
3986                .items_center()
3987                .gap_2()
3988                .child(
3989                    Label::new("Applying...")
3990                        .size(LabelSize::Small)
3991                        .with_animation(
3992                            ("applying-step-transformation-label", id),
3993                            Animation::new(Duration::from_secs(2))
3994                                .repeat()
3995                                .with_easing(pulsating_between(0.4, 0.8)),
3996                            |label, delta| label.alpha(delta),
3997                        ),
3998                )
3999                .child(
4000                    IconButton::new(("stop-transformation", id), IconName::Stop)
4001                        .icon_size(IconSize::Small)
4002                        .icon_color(Color::Error)
4003                        .style(ButtonStyle::Subtle)
4004                        .tooltip({
4005                            let step_range = step_range.clone();
4006                            let editor = editor.clone();
4007                            move |cx| {
4008                                cx.new_view(|cx| {
4009                                    let tooltip = Tooltip::new("Stop Transformation");
4010                                    if display_keybind_in_tooltip(&step_range, &editor, cx) {
4011                                        tooltip.key_binding(KeyBinding::for_action_in(
4012                                            &editor::actions::Cancel,
4013                                            &focus_handle,
4014                                            cx,
4015                                        ))
4016                                    } else {
4017                                        tooltip
4018                                    }
4019                                })
4020                                .into()
4021                            }
4022                        })
4023                        .on_click({
4024                            let editor = editor.clone();
4025                            let step_range = step_range.clone();
4026                            move |_, cx| {
4027                                editor
4028                                    .update(cx, |this, cx| {
4029                                        this.stop_workflow_step(step_range.clone(), cx)
4030                                    })
4031                                    .ok();
4032                            }
4033                        }),
4034                )
4035                .into_any_element(),
4036            WorkflowStepStatus::Done => h_flex()
4037                .gap_1()
4038                .child(
4039                    IconButton::new(("stop-transformation", id), IconName::Close)
4040                        .icon_size(IconSize::Small)
4041                        .style(ButtonStyle::Tinted(TintColor::Negative))
4042                        .tooltip({
4043                            let focus_handle = focus_handle.clone();
4044                            let editor = editor.clone();
4045                            let step_range = step_range.clone();
4046                            move |cx| {
4047                                cx.new_view(|cx| {
4048                                    let tooltip = Tooltip::new("Reject Transformation");
4049                                    if display_keybind_in_tooltip(&step_range, &editor, cx) {
4050                                        tooltip.key_binding(KeyBinding::for_action_in(
4051                                            &editor::actions::Cancel,
4052                                            &focus_handle,
4053                                            cx,
4054                                        ))
4055                                    } else {
4056                                        tooltip
4057                                    }
4058                                })
4059                                .into()
4060                            }
4061                        })
4062                        .on_click({
4063                            let editor = editor.clone();
4064                            let step_range = step_range.clone();
4065                            move |_, cx| {
4066                                editor
4067                                    .update(cx, |this, cx| {
4068                                        this.reject_workflow_step(step_range.clone(), cx);
4069                                    })
4070                                    .ok();
4071                            }
4072                        }),
4073                )
4074                .child(
4075                    Button::new(("confirm-workflow-step", id), "Accept")
4076                        .icon(IconName::Check)
4077                        .icon_position(IconPosition::Start)
4078                        .icon_size(IconSize::Small)
4079                        .label_size(LabelSize::Small)
4080                        .style(ButtonStyle::Tinted(TintColor::Positive))
4081                        .tooltip({
4082                            let editor = editor.clone();
4083                            let step_range = step_range.clone();
4084                            move |cx| {
4085                                cx.new_view(|cx| {
4086                                    let tooltip = Tooltip::new("Accept Transformation");
4087                                    if display_keybind_in_tooltip(&step_range, &editor, cx) {
4088                                        tooltip.key_binding(KeyBinding::for_action_in(
4089                                            &Assist,
4090                                            &focus_handle,
4091                                            cx,
4092                                        ))
4093                                    } else {
4094                                        tooltip
4095                                    }
4096                                })
4097                                .into()
4098                            }
4099                        })
4100                        .on_click({
4101                            let editor = editor.clone();
4102                            let step_range = step_range.clone();
4103                            move |_, cx| {
4104                                editor
4105                                    .update(cx, |this, cx| {
4106                                        this.confirm_workflow_step(step_range.clone(), cx);
4107                                    })
4108                                    .ok();
4109                            }
4110                        }),
4111                )
4112                .into_any_element(),
4113            WorkflowStepStatus::Confirmed => h_flex()
4114                .child(
4115                    Button::new(("revert-workflow-step", id), "Undo")
4116                        .style(ButtonStyle::Filled)
4117                        .icon(Some(IconName::Undo))
4118                        .icon_position(IconPosition::Start)
4119                        .icon_size(IconSize::Small)
4120                        .label_size(LabelSize::Small)
4121                        .on_click({
4122                            let editor = editor.clone();
4123                            let step_range = step_range.clone();
4124                            move |_, cx| {
4125                                editor
4126                                    .update(cx, |this, cx| {
4127                                        this.undo_workflow_step(step_range.clone(), cx);
4128                                    })
4129                                    .ok();
4130                            }
4131                        }),
4132                )
4133                .into_any_element(),
4134        }
4135    }
4136
4137    fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
4138        use feature_flags::FeatureFlagAppExt;
4139        let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
4140            assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
4141        });
4142
4143        if nudge.map_or(false, |value| value) {
4144            Some(
4145                h_flex()
4146                    .p_3()
4147                    .border_b_1()
4148                    .border_color(cx.theme().colors().border_variant)
4149                    .bg(cx.theme().colors().editor_background)
4150                    .justify_between()
4151                    .child(
4152                        h_flex()
4153                            .gap_3()
4154                            .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
4155                            .child(Label::new("Zed AI is here! Get started by signing in →")),
4156                    )
4157                    .child(
4158                        Button::new("sign-in", "Sign in")
4159                            .size(ButtonSize::Compact)
4160                            .style(ButtonStyle::Filled)
4161                            .on_click(cx.listener(|this, _event, cx| {
4162                                let client = this
4163                                    .workspace
4164                                    .update(cx, |workspace, _| workspace.client().clone())
4165                                    .log_err();
4166
4167                                if let Some(client) = client {
4168                                    cx.spawn(|this, mut cx| async move {
4169                                        client.authenticate_and_connect(true, &mut cx).await?;
4170                                        this.update(&mut cx, |_, cx| cx.notify())
4171                                    })
4172                                    .detach_and_log_err(cx)
4173                                }
4174                            })),
4175                    )
4176                    .into_any_element(),
4177            )
4178        } else if let Some(configuration_error) = configuration_error(cx) {
4179            let label = match configuration_error {
4180                ConfigurationError::NoProvider => "No LLM provider selected.",
4181                ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
4182            };
4183            Some(
4184                h_flex()
4185                    .px_3()
4186                    .py_2()
4187                    .border_b_1()
4188                    .border_color(cx.theme().colors().border_variant)
4189                    .bg(cx.theme().colors().editor_background)
4190                    .justify_between()
4191                    .child(
4192                        h_flex()
4193                            .gap_3()
4194                            .child(
4195                                Icon::new(IconName::Warning)
4196                                    .size(IconSize::Small)
4197                                    .color(Color::Warning),
4198                            )
4199                            .child(Label::new(label)),
4200                    )
4201                    .child(
4202                        Button::new("open-configuration", "Configure Providers")
4203                            .size(ButtonSize::Compact)
4204                            .icon(Some(IconName::SlidersVertical))
4205                            .icon_size(IconSize::Small)
4206                            .icon_position(IconPosition::Start)
4207                            .style(ButtonStyle::Filled)
4208                            .on_click({
4209                                let focus_handle = self.focus_handle(cx).clone();
4210                                move |_event, cx| {
4211                                    focus_handle.dispatch_action(&ShowConfiguration, cx);
4212                                }
4213                            }),
4214                    )
4215                    .into_any_element(),
4216            )
4217        } else {
4218            None
4219        }
4220    }
4221
4222    fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4223        let focus_handle = self.focus_handle(cx).clone();
4224        let button_text = match self.active_workflow_step() {
4225            Some((_, step)) => match step.status(cx) {
4226                WorkflowStepStatus::Error(_) => "Retry Step Resolution",
4227                WorkflowStepStatus::Resolving => "Transform",
4228                WorkflowStepStatus::Idle => "Transform",
4229                WorkflowStepStatus::Pending => "Applying...",
4230                WorkflowStepStatus::Done => "Accept",
4231                WorkflowStepStatus::Confirmed => "Send",
4232            },
4233            None => "Send",
4234        };
4235
4236        let (style, tooltip) = match token_state(&self.context, cx) {
4237            Some(TokenState::NoTokensLeft { .. }) => (
4238                ButtonStyle::Tinted(TintColor::Negative),
4239                Some(Tooltip::text("Token limit reached", cx)),
4240            ),
4241            Some(TokenState::HasMoreTokens {
4242                over_warn_threshold,
4243                ..
4244            }) => {
4245                let (style, tooltip) = if over_warn_threshold {
4246                    (
4247                        ButtonStyle::Tinted(TintColor::Warning),
4248                        Some(Tooltip::text("Token limit is close to exhaustion", cx)),
4249                    )
4250                } else {
4251                    (ButtonStyle::Filled, None)
4252                };
4253                (style, tooltip)
4254            }
4255            None => (ButtonStyle::Filled, None),
4256        };
4257
4258        let provider = LanguageModelRegistry::read_global(cx).active_provider();
4259
4260        let has_configuration_error = configuration_error(cx).is_some();
4261        let needs_to_accept_terms = self.show_accept_terms
4262            && provider
4263                .as_ref()
4264                .map_or(false, |provider| provider.must_accept_terms(cx));
4265        let disabled = has_configuration_error || needs_to_accept_terms;
4266
4267        ButtonLike::new("send_button")
4268            .disabled(disabled)
4269            .style(style)
4270            .when_some(tooltip, |button, tooltip| {
4271                button.tooltip(move |_| tooltip.clone())
4272            })
4273            .layer(ElevationIndex::ModalSurface)
4274            .child(Label::new(button_text))
4275            .children(
4276                KeyBinding::for_action_in(&Assist, &focus_handle, cx)
4277                    .map(|binding| binding.into_any_element()),
4278            )
4279            .on_click(move |_event, cx| {
4280                focus_handle.dispatch_action(&Assist, cx);
4281            })
4282    }
4283}
4284
4285/// Returns the contents of the *outermost* fenced code block that contains the given offset.
4286fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
4287    const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
4288    const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
4289
4290    let layer = snapshot.syntax_layers().next()?;
4291
4292    let root_node = layer.node();
4293    let mut cursor = root_node.walk();
4294
4295    // Go to the first child for the given offset
4296    while cursor.goto_first_child_for_byte(offset).is_some() {
4297        // If we're at the end of the node, go to the next one.
4298        // Example: if you have a fenced-code-block, and you're on the start of the line
4299        // right after the closing ```, you want to skip the fenced-code-block and
4300        // go to the next sibling.
4301        if cursor.node().end_byte() == offset {
4302            cursor.goto_next_sibling();
4303        }
4304
4305        if cursor.node().start_byte() > offset {
4306            break;
4307        }
4308
4309        // We found the fenced code block.
4310        if cursor.node().kind() == CODE_BLOCK_NODE {
4311            // Now we need to find the child node that contains the code.
4312            cursor.goto_first_child();
4313            loop {
4314                if cursor.node().kind() == CODE_BLOCK_CONTENT {
4315                    return Some(cursor.node().byte_range());
4316                }
4317                if !cursor.goto_next_sibling() {
4318                    break;
4319                }
4320            }
4321        }
4322    }
4323
4324    None
4325}
4326
4327fn render_fold_icon_button(
4328    editor: WeakView<Editor>,
4329    icon: IconName,
4330    label: SharedString,
4331) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut WindowContext) -> AnyElement> {
4332    Arc::new(move |fold_id, fold_range, _cx| {
4333        let editor = editor.clone();
4334        ButtonLike::new(fold_id)
4335            .style(ButtonStyle::Filled)
4336            .layer(ElevationIndex::ElevatedSurface)
4337            .child(Icon::new(icon))
4338            .child(Label::new(label.clone()).single_line())
4339            .on_click(move |_, cx| {
4340                editor
4341                    .update(cx, |editor, cx| {
4342                        let buffer_start = fold_range
4343                            .start
4344                            .to_point(&editor.buffer().read(cx).read(cx));
4345                        let buffer_row = MultiBufferRow(buffer_start.row);
4346                        editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4347                    })
4348                    .ok();
4349            })
4350            .into_any_element()
4351    })
4352}
4353
4354#[derive(Debug, Clone, Serialize, Deserialize)]
4355struct CopyMetadata {
4356    creases: Vec<SelectedCreaseMetadata>,
4357}
4358
4359#[derive(Debug, Clone, Serialize, Deserialize)]
4360struct SelectedCreaseMetadata {
4361    range_relative_to_selection: Range<usize>,
4362    crease: CreaseMetadata,
4363}
4364
4365impl EventEmitter<EditorEvent> for ContextEditor {}
4366impl EventEmitter<SearchEvent> for ContextEditor {}
4367
4368impl Render for ContextEditor {
4369    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4370        let provider = LanguageModelRegistry::read_global(cx).active_provider();
4371        let accept_terms = if self.show_accept_terms {
4372            provider
4373                .as_ref()
4374                .and_then(|provider| provider.render_accept_terms(cx))
4375        } else {
4376            None
4377        };
4378        let focus_handle = self
4379            .workspace
4380            .update(cx, |workspace, cx| {
4381                Some(workspace.active_item_as::<Editor>(cx)?.focus_handle(cx))
4382            })
4383            .ok()
4384            .flatten();
4385        v_flex()
4386            .key_context("ContextEditor")
4387            .capture_action(cx.listener(ContextEditor::cancel))
4388            .capture_action(cx.listener(ContextEditor::save))
4389            .capture_action(cx.listener(ContextEditor::copy))
4390            .capture_action(cx.listener(ContextEditor::cut))
4391            .capture_action(cx.listener(ContextEditor::paste))
4392            .capture_action(cx.listener(ContextEditor::cycle_message_role))
4393            .capture_action(cx.listener(ContextEditor::confirm_command))
4394            .on_action(cx.listener(ContextEditor::assist))
4395            .on_action(cx.listener(ContextEditor::split))
4396            .size_full()
4397            .children(self.render_notice(cx))
4398            .child(
4399                div()
4400                    .flex_grow()
4401                    .bg(cx.theme().colors().editor_background)
4402                    .child(self.editor.clone()),
4403            )
4404            .when_some(accept_terms, |this, element| {
4405                this.child(
4406                    div()
4407                        .absolute()
4408                        .right_3()
4409                        .bottom_12()
4410                        .max_w_96()
4411                        .py_2()
4412                        .px_3()
4413                        .elevation_2(cx)
4414                        .bg(cx.theme().colors().surface_background)
4415                        .occlude()
4416                        .child(element),
4417                )
4418            })
4419            .when_some(self.error_message.clone(), |this, error_message| {
4420                this.child(
4421                    div()
4422                        .absolute()
4423                        .right_3()
4424                        .bottom_12()
4425                        .max_w_96()
4426                        .py_2()
4427                        .px_3()
4428                        .elevation_2(cx)
4429                        .occlude()
4430                        .child(
4431                            v_flex()
4432                                .gap_0p5()
4433                                .child(
4434                                    h_flex()
4435                                        .gap_1p5()
4436                                        .items_center()
4437                                        .child(Icon::new(IconName::XCircle).color(Color::Error))
4438                                        .child(
4439                                            Label::new("Error interacting with language model")
4440                                                .weight(FontWeight::MEDIUM),
4441                                        ),
4442                                )
4443                                .child(
4444                                    div()
4445                                        .id("error-message")
4446                                        .max_h_24()
4447                                        .overflow_y_scroll()
4448                                        .child(Label::new(error_message)),
4449                                )
4450                                .child(h_flex().justify_end().mt_1().child(
4451                                    Button::new("dismiss", "Dismiss").on_click(cx.listener(
4452                                        |this, _, cx| {
4453                                            this.error_message = None;
4454                                            cx.notify();
4455                                        },
4456                                    )),
4457                                )),
4458                        ),
4459                )
4460            })
4461            .child(
4462                h_flex().w_full().relative().child(
4463                    h_flex()
4464                        .p_2()
4465                        .w_full()
4466                        .border_t_1()
4467                        .border_color(cx.theme().colors().border_variant)
4468                        .bg(cx.theme().colors().editor_background)
4469                        .child(
4470                            h_flex()
4471                                .gap_2()
4472                                .child(render_inject_context_menu(cx.view().downgrade(), cx))
4473                                .child(
4474                                    IconButton::new("quote-button", IconName::Quote)
4475                                        .icon_size(IconSize::Small)
4476                                        .on_click(|_, cx| {
4477                                            cx.dispatch_action(QuoteSelection.boxed_clone());
4478                                        })
4479                                        .tooltip(move |cx| {
4480                                            cx.new_view(|cx| {
4481                                                Tooltip::new("Insert Selection").key_binding(
4482                                                    focus_handle.as_ref().and_then(|handle| {
4483                                                        KeyBinding::for_action_in(
4484                                                            &QuoteSelection,
4485                                                            &handle,
4486                                                            cx,
4487                                                        )
4488                                                    }),
4489                                                )
4490                                            })
4491                                            .into()
4492                                        }),
4493                                ),
4494                        )
4495                        .child(
4496                            h_flex()
4497                                .w_full()
4498                                .justify_end()
4499                                .child(div().child(self.render_send_button(cx))),
4500                        ),
4501                ),
4502            )
4503    }
4504}
4505
4506impl FocusableView for ContextEditor {
4507    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4508        self.editor.focus_handle(cx)
4509    }
4510}
4511
4512impl Item for ContextEditor {
4513    type Event = editor::EditorEvent;
4514
4515    fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
4516        Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
4517    }
4518
4519    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
4520        match event {
4521            EditorEvent::Edited { .. } => {
4522                f(item::ItemEvent::Edit);
4523            }
4524            EditorEvent::TitleChanged => {
4525                f(item::ItemEvent::UpdateTab);
4526            }
4527            _ => {}
4528        }
4529    }
4530
4531    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
4532        Some(self.title(cx).to_string().into())
4533    }
4534
4535    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
4536        Some(Box::new(handle.clone()))
4537    }
4538
4539    fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
4540        self.editor.update(cx, |editor, cx| {
4541            Item::set_nav_history(editor, nav_history, cx)
4542        })
4543    }
4544
4545    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
4546        self.editor
4547            .update(cx, |editor, cx| Item::navigate(editor, data, cx))
4548    }
4549
4550    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
4551        self.editor.update(cx, Item::deactivated)
4552    }
4553}
4554
4555impl SearchableItem for ContextEditor {
4556    type Match = <Editor as SearchableItem>::Match;
4557
4558    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
4559        self.editor.update(cx, |editor, cx| {
4560            editor.clear_matches(cx);
4561        });
4562    }
4563
4564    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4565        self.editor
4566            .update(cx, |editor, cx| editor.update_matches(matches, cx));
4567    }
4568
4569    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
4570        self.editor
4571            .update(cx, |editor, cx| editor.query_suggestion(cx))
4572    }
4573
4574    fn activate_match(
4575        &mut self,
4576        index: usize,
4577        matches: &[Self::Match],
4578        cx: &mut ViewContext<Self>,
4579    ) {
4580        self.editor.update(cx, |editor, cx| {
4581            editor.activate_match(index, matches, cx);
4582        });
4583    }
4584
4585    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4586        self.editor
4587            .update(cx, |editor, cx| editor.select_matches(matches, cx));
4588    }
4589
4590    fn replace(
4591        &mut self,
4592        identifier: &Self::Match,
4593        query: &project::search::SearchQuery,
4594        cx: &mut ViewContext<Self>,
4595    ) {
4596        self.editor
4597            .update(cx, |editor, cx| editor.replace(identifier, query, cx));
4598    }
4599
4600    fn find_matches(
4601        &mut self,
4602        query: Arc<project::search::SearchQuery>,
4603        cx: &mut ViewContext<Self>,
4604    ) -> Task<Vec<Self::Match>> {
4605        self.editor
4606            .update(cx, |editor, cx| editor.find_matches(query, cx))
4607    }
4608
4609    fn active_match_index(
4610        &mut self,
4611        matches: &[Self::Match],
4612        cx: &mut ViewContext<Self>,
4613    ) -> Option<usize> {
4614        self.editor
4615            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
4616    }
4617}
4618
4619impl FollowableItem for ContextEditor {
4620    fn remote_id(&self) -> Option<workspace::ViewId> {
4621        self.remote_id
4622    }
4623
4624    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
4625        let context = self.context.read(cx);
4626        Some(proto::view::Variant::ContextEditor(
4627            proto::view::ContextEditor {
4628                context_id: context.id().to_proto(),
4629                editor: if let Some(proto::view::Variant::Editor(proto)) =
4630                    self.editor.read(cx).to_state_proto(cx)
4631                {
4632                    Some(proto)
4633                } else {
4634                    None
4635                },
4636            },
4637        ))
4638    }
4639
4640    fn from_state_proto(
4641        workspace: View<Workspace>,
4642        id: workspace::ViewId,
4643        state: &mut Option<proto::view::Variant>,
4644        cx: &mut WindowContext,
4645    ) -> Option<Task<Result<View<Self>>>> {
4646        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
4647            return None;
4648        };
4649        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
4650            unreachable!()
4651        };
4652
4653        let context_id = ContextId::from_proto(state.context_id);
4654        let editor_state = state.editor?;
4655
4656        let (project, panel) = workspace.update(cx, |workspace, cx| {
4657            Some((
4658                workspace.project().clone(),
4659                workspace.panel::<AssistantPanel>(cx)?,
4660            ))
4661        })?;
4662
4663        let context_editor =
4664            panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
4665
4666        Some(cx.spawn(|mut cx| async move {
4667            let context_editor = context_editor.await?;
4668            context_editor
4669                .update(&mut cx, |context_editor, cx| {
4670                    context_editor.remote_id = Some(id);
4671                    context_editor.editor.update(cx, |editor, cx| {
4672                        editor.apply_update_proto(
4673                            &project,
4674                            proto::update_view::Variant::Editor(proto::update_view::Editor {
4675                                selections: editor_state.selections,
4676                                pending_selection: editor_state.pending_selection,
4677                                scroll_top_anchor: editor_state.scroll_top_anchor,
4678                                scroll_x: editor_state.scroll_y,
4679                                scroll_y: editor_state.scroll_y,
4680                                ..Default::default()
4681                            }),
4682                            cx,
4683                        )
4684                    })
4685                })?
4686                .await?;
4687            Ok(context_editor)
4688        }))
4689    }
4690
4691    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
4692        Editor::to_follow_event(event)
4693    }
4694
4695    fn add_event_to_update_proto(
4696        &self,
4697        event: &Self::Event,
4698        update: &mut Option<proto::update_view::Variant>,
4699        cx: &WindowContext,
4700    ) -> bool {
4701        self.editor
4702            .read(cx)
4703            .add_event_to_update_proto(event, update, cx)
4704    }
4705
4706    fn apply_update_proto(
4707        &mut self,
4708        project: &Model<Project>,
4709        message: proto::update_view::Variant,
4710        cx: &mut ViewContext<Self>,
4711    ) -> Task<Result<()>> {
4712        self.editor.update(cx, |editor, cx| {
4713            editor.apply_update_proto(project, message, cx)
4714        })
4715    }
4716
4717    fn is_project_item(&self, _cx: &WindowContext) -> bool {
4718        true
4719    }
4720
4721    fn set_leader_peer_id(
4722        &mut self,
4723        leader_peer_id: Option<proto::PeerId>,
4724        cx: &mut ViewContext<Self>,
4725    ) {
4726        self.editor.update(cx, |editor, cx| {
4727            editor.set_leader_peer_id(leader_peer_id, cx)
4728        })
4729    }
4730
4731    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
4732        if existing.context.read(cx).id() == self.context.read(cx).id() {
4733            Some(item::Dedup::KeepExisting)
4734        } else {
4735            None
4736        }
4737    }
4738}
4739
4740pub struct ContextEditorToolbarItem {
4741    fs: Arc<dyn Fs>,
4742    workspace: WeakView<Workspace>,
4743    active_context_editor: Option<WeakView<ContextEditor>>,
4744    model_summary_editor: View<Editor>,
4745    model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4746}
4747
4748fn active_editor_focus_handle(
4749    workspace: &WeakView<Workspace>,
4750    cx: &WindowContext<'_>,
4751) -> Option<FocusHandle> {
4752    workspace.upgrade().and_then(|workspace| {
4753        Some(
4754            workspace
4755                .read(cx)
4756                .active_item_as::<Editor>(cx)?
4757                .focus_handle(cx),
4758        )
4759    })
4760}
4761
4762fn render_inject_context_menu(
4763    active_context_editor: WeakView<ContextEditor>,
4764    cx: &mut WindowContext<'_>,
4765) -> impl IntoElement {
4766    let commands = SlashCommandRegistry::global(cx);
4767
4768    slash_command_picker::SlashCommandSelector::new(
4769        commands.clone(),
4770        active_context_editor,
4771        IconButton::new("trigger", IconName::SlashSquare)
4772            .icon_size(IconSize::Small)
4773            .tooltip(|cx| {
4774                Tooltip::with_meta("Insert Context", None, "Type / to insert via keyboard", cx)
4775            }),
4776    )
4777}
4778
4779impl ContextEditorToolbarItem {
4780    pub fn new(
4781        workspace: &Workspace,
4782        model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4783        model_summary_editor: View<Editor>,
4784    ) -> Self {
4785        Self {
4786            fs: workspace.app_state().fs.clone(),
4787            workspace: workspace.weak_handle(),
4788            active_context_editor: None,
4789            model_summary_editor,
4790            model_selector_menu_handle,
4791        }
4792    }
4793
4794    fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
4795        let context = &self
4796            .active_context_editor
4797            .as_ref()?
4798            .upgrade()?
4799            .read(cx)
4800            .context;
4801        let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
4802            TokenState::NoTokensLeft {
4803                max_token_count,
4804                token_count,
4805            } => (Color::Error, token_count, max_token_count),
4806            TokenState::HasMoreTokens {
4807                max_token_count,
4808                token_count,
4809                over_warn_threshold,
4810            } => {
4811                let color = if over_warn_threshold {
4812                    Color::Warning
4813                } else {
4814                    Color::Muted
4815                };
4816                (color, token_count, max_token_count)
4817            }
4818        };
4819        Some(
4820            h_flex()
4821                .gap_0p5()
4822                .child(
4823                    Label::new(humanize_token_count(token_count))
4824                        .size(LabelSize::Small)
4825                        .color(token_count_color),
4826                )
4827                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
4828                .child(
4829                    Label::new(humanize_token_count(max_token_count))
4830                        .size(LabelSize::Small)
4831                        .color(Color::Muted),
4832                ),
4833        )
4834    }
4835}
4836
4837impl Render for ContextEditorToolbarItem {
4838    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4839        let left_side = h_flex()
4840            .pl_1()
4841            .gap_2()
4842            .flex_1()
4843            .min_w(rems(DEFAULT_TAB_TITLE.len() as f32))
4844            .when(self.active_context_editor.is_some(), |left_side| {
4845                left_side.child(self.model_summary_editor.clone())
4846            });
4847        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
4848        let active_model = LanguageModelRegistry::read_global(cx).active_model();
4849        let weak_self = cx.view().downgrade();
4850        let right_side = h_flex()
4851            .gap_2()
4852            // TODO display this in a nicer way, once we have a design for it.
4853            // .children({
4854            //     let project = self
4855            //         .workspace
4856            //         .upgrade()
4857            //         .map(|workspace| workspace.read(cx).project().downgrade());
4858            //
4859            //     let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
4860            //         project.and_then(|project| db.remaining_summaries(&project, cx))
4861            //     });
4862
4863            //     scan_items_remaining
4864            //         .map(|remaining_items| format!("Files to scan: {}", remaining_items))
4865            // })
4866            .child(
4867                ModelSelector::new(
4868                    self.fs.clone(),
4869                    ButtonLike::new("active-model")
4870                        .style(ButtonStyle::Subtle)
4871                        .child(
4872                            h_flex()
4873                                .w_full()
4874                                .gap_0p5()
4875                                .child(
4876                                    div()
4877                                        .overflow_x_hidden()
4878                                        .flex_grow()
4879                                        .whitespace_nowrap()
4880                                        .child(match (active_provider, active_model) {
4881                                            (Some(provider), Some(model)) => h_flex()
4882                                                .gap_1()
4883                                                .child(
4884                                                    Icon::new(model.icon().unwrap_or_else(|| provider.icon()))
4885                                                        .color(Color::Muted)
4886                                                        .size(IconSize::XSmall),
4887                                                )
4888                                                .child(
4889                                                    Label::new(model.name().0)
4890                                                        .size(LabelSize::Small)
4891                                                        .color(Color::Muted),
4892                                                )
4893                                                .into_any_element(),
4894                                            _ => Label::new("No model selected")
4895                                                .size(LabelSize::Small)
4896                                                .color(Color::Muted)
4897                                                .into_any_element(),
4898                                        }),
4899                                )
4900                                .child(
4901                                    Icon::new(IconName::ChevronDown)
4902                                        .color(Color::Muted)
4903                                        .size(IconSize::XSmall),
4904                                ),
4905                        )
4906                        .tooltip(move |cx| {
4907                            Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
4908                        }),
4909                )
4910                .with_handle(self.model_selector_menu_handle.clone()),
4911            )
4912            .children(self.render_remaining_tokens(cx))
4913            .child(
4914                PopoverMenu::new("context-editor-popover")
4915                    .trigger(
4916                        IconButton::new("context-editor-trigger", IconName::EllipsisVertical)
4917                            .icon_size(IconSize::Small)
4918                            .tooltip(|cx| Tooltip::text("Open Context Options", cx)),
4919                    )
4920                    .menu({
4921                        let weak_self = weak_self.clone();
4922                        move |cx| {
4923                            let weak_self = weak_self.clone();
4924                            Some(ContextMenu::build(cx, move |menu, cx| {
4925                                let context = weak_self
4926                                    .update(cx, |this, cx| {
4927                                        active_editor_focus_handle(&this.workspace, cx)
4928                                    })
4929                                    .ok()
4930                                    .flatten();
4931                                menu.when_some(context, |menu, context| menu.context(context))
4932                                    .entry("Regenerate Context Title", None, {
4933                                        let weak_self = weak_self.clone();
4934                                        move |cx| {
4935                                            weak_self
4936                                                .update(cx, |_, cx| {
4937                                                    cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
4938                                                })
4939                                                .ok();
4940                                        }
4941                                    })
4942                                    .custom_entry(
4943                                        |_| {
4944                                            h_flex()
4945                                                .w_full()
4946                                                .justify_between()
4947                                                .gap_2()
4948                                                .child(Label::new("Insert Context"))
4949                                                .child(Label::new("/ command").color(Color::Muted))
4950                                                .into_any()
4951                                        },
4952                                        {
4953                                            let weak_self = weak_self.clone();
4954                                            move |cx| {
4955                                                weak_self
4956                                                    .update(cx, |this, cx| {
4957                                                        if let Some(editor) =
4958                                                        &this.active_context_editor
4959                                                        {
4960                                                            editor
4961                                                                .update(cx, |this, cx| {
4962                                                                    this.slash_menu_handle
4963                                                                        .toggle(cx);
4964                                                                })
4965                                                                .ok();
4966                                                        }
4967                                                    })
4968                                                    .ok();
4969                                            }
4970                                        },
4971                                    )
4972                                    .action("Insert Selection", QuoteSelection.boxed_clone())
4973                            }))
4974                        }
4975                    }),
4976            );
4977
4978        h_flex()
4979            .size_full()
4980            .gap_2()
4981            .justify_between()
4982            .child(left_side)
4983            .child(right_side)
4984    }
4985}
4986
4987impl ToolbarItemView for ContextEditorToolbarItem {
4988    fn set_active_pane_item(
4989        &mut self,
4990        active_pane_item: Option<&dyn ItemHandle>,
4991        cx: &mut ViewContext<Self>,
4992    ) -> ToolbarItemLocation {
4993        self.active_context_editor = active_pane_item
4994            .and_then(|item| item.act_as::<ContextEditor>(cx))
4995            .map(|editor| editor.downgrade());
4996        cx.notify();
4997        if self.active_context_editor.is_none() {
4998            ToolbarItemLocation::Hidden
4999        } else {
5000            ToolbarItemLocation::PrimaryRight
5001        }
5002    }
5003
5004    fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
5005        cx.notify();
5006    }
5007}
5008
5009impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
5010
5011enum ContextEditorToolbarItemEvent {
5012    RegenerateSummary,
5013}
5014impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
5015
5016pub struct ContextHistory {
5017    picker: View<Picker<SavedContextPickerDelegate>>,
5018    _subscriptions: Vec<Subscription>,
5019    assistant_panel: WeakView<AssistantPanel>,
5020}
5021
5022impl ContextHistory {
5023    fn new(
5024        project: Model<Project>,
5025        context_store: Model<ContextStore>,
5026        assistant_panel: WeakView<AssistantPanel>,
5027        cx: &mut ViewContext<Self>,
5028    ) -> Self {
5029        let picker = cx.new_view(|cx| {
5030            Picker::uniform_list(
5031                SavedContextPickerDelegate::new(project, context_store.clone()),
5032                cx,
5033            )
5034            .modal(false)
5035            .max_height(None)
5036        });
5037
5038        let _subscriptions = vec![
5039            cx.observe(&context_store, |this, _, cx| {
5040                this.picker.update(cx, |picker, cx| picker.refresh(cx));
5041            }),
5042            cx.subscribe(&picker, Self::handle_picker_event),
5043        ];
5044
5045        Self {
5046            picker,
5047            _subscriptions,
5048            assistant_panel,
5049        }
5050    }
5051
5052    fn handle_picker_event(
5053        &mut self,
5054        _: View<Picker<SavedContextPickerDelegate>>,
5055        event: &SavedContextPickerEvent,
5056        cx: &mut ViewContext<Self>,
5057    ) {
5058        let SavedContextPickerEvent::Confirmed(context) = event;
5059        self.assistant_panel
5060            .update(cx, |assistant_panel, cx| match context {
5061                ContextMetadata::Remote(metadata) => {
5062                    assistant_panel
5063                        .open_remote_context(metadata.id.clone(), cx)
5064                        .detach_and_log_err(cx);
5065                }
5066                ContextMetadata::Saved(metadata) => {
5067                    assistant_panel
5068                        .open_saved_context(metadata.path.clone(), cx)
5069                        .detach_and_log_err(cx);
5070                }
5071            })
5072            .ok();
5073    }
5074}
5075
5076#[derive(Debug, PartialEq, Eq, Clone, Copy)]
5077pub enum WorkflowAssistStatus {
5078    Pending,
5079    Confirmed,
5080    Done,
5081    Idle,
5082}
5083
5084impl WorkflowAssist {
5085    pub fn status(&self, cx: &AppContext) -> WorkflowAssistStatus {
5086        let assistant = InlineAssistant::global(cx);
5087        if self
5088            .assist_ids
5089            .iter()
5090            .any(|assist_id| assistant.assist_status(*assist_id, cx).is_pending())
5091        {
5092            WorkflowAssistStatus::Pending
5093        } else if self
5094            .assist_ids
5095            .iter()
5096            .all(|assist_id| assistant.assist_status(*assist_id, cx).is_confirmed())
5097        {
5098            WorkflowAssistStatus::Confirmed
5099        } else if self
5100            .assist_ids
5101            .iter()
5102            .all(|assist_id| assistant.assist_status(*assist_id, cx).is_done())
5103        {
5104            WorkflowAssistStatus::Done
5105        } else {
5106            WorkflowAssistStatus::Idle
5107        }
5108    }
5109}
5110
5111impl Render for ContextHistory {
5112    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
5113        div().size_full().child(self.picker.clone())
5114    }
5115}
5116
5117impl FocusableView for ContextHistory {
5118    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
5119        self.picker.focus_handle(cx)
5120    }
5121}
5122
5123impl EventEmitter<()> for ContextHistory {}
5124
5125impl Item for ContextHistory {
5126    type Event = ();
5127
5128    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
5129        Some("History".into())
5130    }
5131}
5132
5133pub struct ConfigurationView {
5134    focus_handle: FocusHandle,
5135    configuration_views: HashMap<LanguageModelProviderId, AnyView>,
5136    _registry_subscription: Subscription,
5137}
5138
5139impl ConfigurationView {
5140    fn new(cx: &mut ViewContext<Self>) -> Self {
5141        let focus_handle = cx.focus_handle();
5142
5143        let registry_subscription = cx.subscribe(
5144            &LanguageModelRegistry::global(cx),
5145            |this, _, event: &language_model::Event, cx| match event {
5146                language_model::Event::AddedProvider(provider_id) => {
5147                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
5148                    if let Some(provider) = provider {
5149                        this.add_configuration_view(&provider, cx);
5150                    }
5151                }
5152                language_model::Event::RemovedProvider(provider_id) => {
5153                    this.remove_configuration_view(provider_id);
5154                }
5155                _ => {}
5156            },
5157        );
5158
5159        let mut this = Self {
5160            focus_handle,
5161            configuration_views: HashMap::default(),
5162            _registry_subscription: registry_subscription,
5163        };
5164        this.build_configuration_views(cx);
5165        this
5166    }
5167
5168    fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
5169        let providers = LanguageModelRegistry::read_global(cx).providers();
5170        for provider in providers {
5171            self.add_configuration_view(&provider, cx);
5172        }
5173    }
5174
5175    fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
5176        self.configuration_views.remove(provider_id);
5177    }
5178
5179    fn add_configuration_view(
5180        &mut self,
5181        provider: &Arc<dyn LanguageModelProvider>,
5182        cx: &mut ViewContext<Self>,
5183    ) {
5184        let configuration_view = provider.configuration_view(cx);
5185        self.configuration_views
5186            .insert(provider.id(), configuration_view);
5187    }
5188
5189    fn render_provider_view(
5190        &mut self,
5191        provider: &Arc<dyn LanguageModelProvider>,
5192        cx: &mut ViewContext<Self>,
5193    ) -> Div {
5194        let provider_id = provider.id().0.clone();
5195        let provider_name = provider.name().0.clone();
5196        let configuration_view = self.configuration_views.get(&provider.id()).cloned();
5197
5198        let open_new_context = cx.listener({
5199            let provider = provider.clone();
5200            move |_, _, cx| {
5201                cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
5202                    provider.clone(),
5203                ))
5204            }
5205        });
5206
5207        v_flex()
5208            .gap_2()
5209            .child(
5210                h_flex()
5211                    .justify_between()
5212                    .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
5213                    .when(provider.is_authenticated(cx), move |this| {
5214                        this.child(
5215                            h_flex().justify_end().child(
5216                                Button::new(
5217                                    SharedString::from(format!("new-context-{provider_id}")),
5218                                    "Open new context",
5219                                )
5220                                .icon_position(IconPosition::Start)
5221                                .icon(IconName::Plus)
5222                                .style(ButtonStyle::Filled)
5223                                .layer(ElevationIndex::ModalSurface)
5224                                .on_click(open_new_context),
5225                            ),
5226                        )
5227                    }),
5228            )
5229            .child(
5230                div()
5231                    .p(Spacing::Large.rems(cx))
5232                    .bg(cx.theme().colors().surface_background)
5233                    .border_1()
5234                    .border_color(cx.theme().colors().border_variant)
5235                    .rounded_md()
5236                    .when(configuration_view.is_none(), |this| {
5237                        this.child(div().child(Label::new(format!(
5238                            "No configuration view for {}",
5239                            provider_name
5240                        ))))
5241                    })
5242                    .when_some(configuration_view, |this, configuration_view| {
5243                        this.child(configuration_view)
5244                    }),
5245            )
5246    }
5247}
5248
5249impl Render for ConfigurationView {
5250    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
5251        let providers = LanguageModelRegistry::read_global(cx).providers();
5252        let provider_views = providers
5253            .into_iter()
5254            .map(|provider| self.render_provider_view(&provider, cx))
5255            .collect::<Vec<_>>();
5256
5257        let mut element = v_flex()
5258            .id("assistant-configuration-view")
5259            .track_focus(&self.focus_handle)
5260            .bg(cx.theme().colors().editor_background)
5261            .size_full()
5262            .overflow_y_scroll()
5263            .child(
5264                v_flex()
5265                    .p(Spacing::XXLarge.rems(cx))
5266                    .border_b_1()
5267                    .border_color(cx.theme().colors().border)
5268                    .gap_1()
5269                    .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
5270                    .child(
5271                        Label::new(
5272                            "At least one LLM provider must be configured to use the Assistant.",
5273                        )
5274                        .color(Color::Muted),
5275                    ),
5276            )
5277            .child(
5278                v_flex()
5279                    .p(Spacing::XXLarge.rems(cx))
5280                    .mt_1()
5281                    .gap_6()
5282                    .flex_1()
5283                    .children(provider_views),
5284            )
5285            .into_any();
5286
5287        // We use a canvas here to get scrolling to work in the ConfigurationView. It's a workaround
5288        // because we couldn't the element to take up the size of the parent.
5289        canvas(
5290            move |bounds, cx| {
5291                element.prepaint_as_root(bounds.origin, bounds.size.into(), cx);
5292                element
5293            },
5294            |_, mut element, cx| {
5295                element.paint(cx);
5296            },
5297        )
5298        .flex_1()
5299        .w_full()
5300    }
5301}
5302
5303pub enum ConfigurationViewEvent {
5304    NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
5305}
5306
5307impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
5308
5309impl FocusableView for ConfigurationView {
5310    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
5311        self.focus_handle.clone()
5312    }
5313}
5314
5315impl Item for ConfigurationView {
5316    type Event = ConfigurationViewEvent;
5317
5318    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
5319        Some("Configuration".into())
5320    }
5321}
5322
5323type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
5324
5325fn render_slash_command_output_toggle(
5326    row: MultiBufferRow,
5327    is_folded: bool,
5328    fold: ToggleFold,
5329    _cx: &mut WindowContext,
5330) -> AnyElement {
5331    Disclosure::new(
5332        ("slash-command-output-fold-indicator", row.0 as u64),
5333        !is_folded,
5334    )
5335    .selected(is_folded)
5336    .on_click(move |_e, cx| fold(!is_folded, cx))
5337    .into_any_element()
5338}
5339
5340fn fold_toggle(
5341    name: &'static str,
5342) -> impl Fn(
5343    MultiBufferRow,
5344    bool,
5345    Arc<dyn Fn(bool, &mut WindowContext<'_>) + Send + Sync>,
5346    &mut WindowContext<'_>,
5347) -> AnyElement {
5348    move |row, is_folded, fold, _cx| {
5349        Disclosure::new((name, row.0 as u64), !is_folded)
5350            .selected(is_folded)
5351            .on_click(move |_e, cx| fold(!is_folded, cx))
5352            .into_any_element()
5353    }
5354}
5355
5356fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) -> FoldPlaceholder {
5357    FoldPlaceholder {
5358        render: Arc::new({
5359            move |fold_id, fold_range, _cx| {
5360                let editor = editor.clone();
5361                ButtonLike::new(fold_id)
5362                    .style(ButtonStyle::Filled)
5363                    .layer(ElevationIndex::ElevatedSurface)
5364                    .child(Icon::new(IconName::TextSnippet))
5365                    .child(Label::new(title.clone()).single_line())
5366                    .on_click(move |_, cx| {
5367                        editor
5368                            .update(cx, |editor, cx| {
5369                                let buffer_start = fold_range
5370                                    .start
5371                                    .to_point(&editor.buffer().read(cx).read(cx));
5372                                let buffer_row = MultiBufferRow(buffer_start.row);
5373                                editor.unfold_at(&UnfoldAt { buffer_row }, cx);
5374                            })
5375                            .ok();
5376                    })
5377                    .into_any_element()
5378            }
5379        }),
5380        constrain_width: false,
5381        merge_adjacent: false,
5382    }
5383}
5384
5385fn render_quote_selection_output_toggle(
5386    row: MultiBufferRow,
5387    is_folded: bool,
5388    fold: ToggleFold,
5389    _cx: &mut WindowContext,
5390) -> AnyElement {
5391    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
5392        .selected(is_folded)
5393        .on_click(move |_e, cx| fold(!is_folded, cx))
5394        .into_any_element()
5395}
5396
5397fn render_pending_slash_command_gutter_decoration(
5398    row: MultiBufferRow,
5399    status: &PendingSlashCommandStatus,
5400    confirm_command: Arc<dyn Fn(&mut WindowContext)>,
5401) -> AnyElement {
5402    let mut icon = IconButton::new(
5403        ("slash-command-gutter-decoration", row.0),
5404        ui::IconName::TriangleRight,
5405    )
5406    .on_click(move |_e, cx| confirm_command(cx))
5407    .icon_size(ui::IconSize::Small)
5408    .size(ui::ButtonSize::None);
5409
5410    match status {
5411        PendingSlashCommandStatus::Idle => {
5412            icon = icon.icon_color(Color::Muted);
5413        }
5414        PendingSlashCommandStatus::Running { .. } => {
5415            icon = icon.selected(true);
5416        }
5417        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
5418    }
5419
5420    icon.into_any_element()
5421}
5422
5423fn render_docs_slash_command_trailer(
5424    row: MultiBufferRow,
5425    command: PendingSlashCommand,
5426    cx: &mut WindowContext,
5427) -> AnyElement {
5428    if command.arguments.is_empty() {
5429        return Empty.into_any();
5430    }
5431    let args = DocsSlashCommandArgs::parse(&command.arguments);
5432
5433    let Some(store) = args
5434        .provider()
5435        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
5436    else {
5437        return Empty.into_any();
5438    };
5439
5440    let Some(package) = args.package() else {
5441        return Empty.into_any();
5442    };
5443
5444    let mut children = Vec::new();
5445
5446    if store.is_indexing(&package) {
5447        children.push(
5448            div()
5449                .id(("crates-being-indexed", row.0))
5450                .child(Icon::new(IconName::ArrowCircle).with_animation(
5451                    "arrow-circle",
5452                    Animation::new(Duration::from_secs(4)).repeat(),
5453                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
5454                ))
5455                .tooltip({
5456                    let package = package.clone();
5457                    move |cx| Tooltip::text(format!("Indexing {package}"), cx)
5458                })
5459                .into_any_element(),
5460        );
5461    }
5462
5463    if let Some(latest_error) = store.latest_error_for_package(&package) {
5464        children.push(
5465            div()
5466                .id(("latest-error", row.0))
5467                .child(
5468                    Icon::new(IconName::Warning)
5469                        .size(IconSize::Small)
5470                        .color(Color::Warning),
5471                )
5472                .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
5473                .into_any_element(),
5474        )
5475    }
5476
5477    let is_indexing = store.is_indexing(&package);
5478    let latest_error = store.latest_error_for_package(&package);
5479
5480    if !is_indexing && latest_error.is_none() {
5481        return Empty.into_any();
5482    }
5483
5484    h_flex().gap_2().children(children).into_any_element()
5485}
5486
5487fn make_lsp_adapter_delegate(
5488    project: &Model<Project>,
5489    cx: &mut AppContext,
5490) -> Result<Arc<dyn LspAdapterDelegate>> {
5491    project.update(cx, |project, cx| {
5492        // TODO: Find the right worktree.
5493        let worktree = project
5494            .worktrees(cx)
5495            .next()
5496            .ok_or_else(|| anyhow!("no worktrees when constructing LocalLspAdapterDelegate"))?;
5497        let http_client = project.client().http_client().clone();
5498        project.lsp_store().update(cx, |lsp_store, cx| {
5499            Ok(LocalLspAdapterDelegate::new(
5500                lsp_store,
5501                &worktree,
5502                http_client,
5503                project.fs().clone(),
5504                cx,
5505            ) as Arc<dyn LspAdapterDelegate>)
5506        })
5507    })
5508}
5509
5510fn slash_command_error_block_renderer(message: String) -> RenderBlock {
5511    Box::new(move |_| {
5512        div()
5513            .pl_6()
5514            .child(
5515                Label::new(format!("error: {}", message))
5516                    .single_line()
5517                    .color(Color::Error),
5518            )
5519            .into_any()
5520    })
5521}
5522
5523enum TokenState {
5524    NoTokensLeft {
5525        max_token_count: usize,
5526        token_count: usize,
5527    },
5528    HasMoreTokens {
5529        max_token_count: usize,
5530        token_count: usize,
5531        over_warn_threshold: bool,
5532    },
5533}
5534
5535fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
5536    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
5537
5538    let model = LanguageModelRegistry::read_global(cx).active_model()?;
5539    let token_count = context.read(cx).token_count()?;
5540    let max_token_count = model.max_token_count();
5541
5542    let remaining_tokens = max_token_count as isize - token_count as isize;
5543    let token_state = if remaining_tokens <= 0 {
5544        TokenState::NoTokensLeft {
5545            max_token_count,
5546            token_count,
5547        }
5548    } else {
5549        let over_warn_threshold =
5550            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
5551        TokenState::HasMoreTokens {
5552            max_token_count,
5553            token_count,
5554            over_warn_threshold,
5555        }
5556    };
5557    Some(token_state)
5558}
5559
5560fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
5561    let image_size = data
5562        .size(0)
5563        .map(|dimension| Pixels::from(u32::from(dimension)));
5564    let image_ratio = image_size.width / image_size.height;
5565    let bounds_ratio = max_size.width / max_size.height;
5566
5567    if image_size.width > max_size.width || image_size.height > max_size.height {
5568        if bounds_ratio > image_ratio {
5569            size(
5570                image_size.width * (max_size.height / image_size.height),
5571                max_size.height,
5572            )
5573        } else {
5574            size(
5575                max_size.width,
5576                image_size.height * (max_size.width / image_size.width),
5577            )
5578        }
5579    } else {
5580        size(image_size.width, image_size.height)
5581    }
5582}
5583
5584enum ConfigurationError {
5585    NoProvider,
5586    ProviderNotAuthenticated,
5587}
5588
5589fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
5590    let provider = LanguageModelRegistry::read_global(cx).active_provider();
5591    let is_authenticated = provider
5592        .as_ref()
5593        .map_or(false, |provider| provider.is_authenticated(cx));
5594
5595    if provider.is_some() && is_authenticated {
5596        return None;
5597    }
5598
5599    if provider.is_none() {
5600        return Some(ConfigurationError::NoProvider);
5601    }
5602
5603    if !is_authenticated {
5604        return Some(ConfigurationError::ProviderNotAuthenticated);
5605    }
5606
5607    None
5608}
5609
5610#[cfg(test)]
5611mod tests {
5612    use super::*;
5613    use gpui::{AppContext, Context};
5614    use language::Buffer;
5615    use unindent::Unindent;
5616
5617    #[gpui::test]
5618    fn test_find_code_blocks(cx: &mut AppContext) {
5619        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
5620
5621        let buffer = cx.new_model(|cx| {
5622            let text = r#"
5623                line 0
5624                line 1
5625                ```rust
5626                fn main() {}
5627                ```
5628                line 5
5629                line 6
5630                line 7
5631                ```go
5632                func main() {}
5633                ```
5634                line 11
5635                ```
5636                this is plain text code block
5637                ```
5638
5639                ```go
5640                func another() {}
5641                ```
5642                line 19
5643            "#
5644            .unindent();
5645            let mut buffer = Buffer::local(text, cx);
5646            buffer.set_language(Some(markdown.clone()), cx);
5647            buffer
5648        });
5649        let snapshot = buffer.read(cx).snapshot();
5650
5651        let code_blocks = vec![
5652            Point::new(3, 0)..Point::new(4, 0),
5653            Point::new(9, 0)..Point::new(10, 0),
5654            Point::new(13, 0)..Point::new(14, 0),
5655            Point::new(17, 0)..Point::new(18, 0),
5656        ]
5657        .into_iter()
5658        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
5659        .collect::<Vec<_>>();
5660
5661        let expected_results = vec![
5662            (0, None),
5663            (1, None),
5664            (2, Some(code_blocks[0].clone())),
5665            (3, Some(code_blocks[0].clone())),
5666            (4, Some(code_blocks[0].clone())),
5667            (5, None),
5668            (6, None),
5669            (7, None),
5670            (8, Some(code_blocks[1].clone())),
5671            (9, Some(code_blocks[1].clone())),
5672            (10, Some(code_blocks[1].clone())),
5673            (11, None),
5674            (12, Some(code_blocks[2].clone())),
5675            (13, Some(code_blocks[2].clone())),
5676            (14, Some(code_blocks[2].clone())),
5677            (15, None),
5678            (16, Some(code_blocks[3].clone())),
5679            (17, Some(code_blocks[3].clone())),
5680            (18, Some(code_blocks[3].clone())),
5681            (19, None),
5682        ];
5683
5684        for (row, expected) in expected_results {
5685            let offset = snapshot.point_to_offset(Point::new(row, 0));
5686            let range = find_surrounding_code_block(&snapshot, offset);
5687            assert_eq!(range, expected, "unexpected result on row {:?}", row);
5688        }
5689    }
5690}