assistant_panel.rs

   1use crate::{
   2    assistant_settings::{AssistantDockPosition, AssistantSettings},
   3    context_inspector::ContextInspector,
   4    humanize_token_count,
   5    prompt_library::open_prompt_library,
   6    prompts::PromptBuilder,
   7    slash_command::{
   8        default_command::DefaultSlashCommand,
   9        docs_command::{DocsSlashCommand, DocsSlashCommandArgs},
  10        file_command::codeblock_fence_for_path,
  11        SlashCommandCompletionProvider, SlashCommandRegistry,
  12    },
  13    terminal_inline_assistant::TerminalInlineAssistant,
  14    Assist, ConfirmCommand, Context, ContextEvent, ContextId, ContextStore, CycleMessageRole,
  15    DebugWorkflowSteps, DeployHistory, DeployPromptLibrary, InlineAssist, InlineAssistId,
  16    InlineAssistant, InsertIntoEditor, MessageStatus, ModelSelector, PendingSlashCommand,
  17    PendingSlashCommandStatus, QuoteSelection, RemoteContextMetadata, ResolvedWorkflowStep,
  18    SavedContextMetadata, Split, ToggleFocus, ToggleModelSelector,
  19};
  20use crate::{ContextStoreEvent, ShowConfiguration};
  21use anyhow::{anyhow, Result};
  22use assistant_slash_command::{SlashCommand, SlashCommandOutputSection};
  23use client::{proto, Client, Status};
  24use collections::{BTreeSet, HashMap, HashSet};
  25use editor::{
  26    actions::{FoldAt, MoveToEndOfLine, Newline, ShowCompletions, UnfoldAt},
  27    display_map::{
  28        BlockContext, BlockDisposition, BlockProperties, BlockStyle, Crease, CustomBlockId,
  29        RenderBlock, ToDisplayPoint,
  30    },
  31    scroll::{Autoscroll, AutoscrollStrategy, ScrollAnchor},
  32    Anchor, Editor, EditorEvent, ExcerptRange, MultiBuffer, RowExt, ToOffset as _, ToPoint,
  33};
  34use editor::{display_map::CreaseId, FoldPlaceholder};
  35use fs::Fs;
  36use gpui::{
  37    canvas, div, percentage, point, pulsating_between, Action, Animation, AnimationExt, AnyElement,
  38    AnyView, AppContext, AsyncWindowContext, ClipboardItem, Context as _, DismissEvent, Empty,
  39    Entity, EntityId, EventEmitter, FocusHandle, FocusableView, FontWeight, InteractiveElement,
  40    IntoElement, Model, ParentElement, Pixels, ReadGlobal, Render, SharedString,
  41    StatefulInteractiveElement, Styled, Subscription, Task, Transformation, UpdateGlobal, View,
  42    ViewContext, VisualContext, WeakView, WindowContext,
  43};
  44use indexed_docs::IndexedDocsStore;
  45use language::{
  46    language_settings::SoftWrap, Capability, LanguageRegistry, LspAdapterDelegate, Point, ToOffset,
  47};
  48use language_model::{
  49    provider::cloud::PROVIDER_ID, LanguageModelProvider, LanguageModelProviderId,
  50    LanguageModelRegistry, Role,
  51};
  52use multi_buffer::MultiBufferRow;
  53use picker::{Picker, PickerDelegate};
  54use project::{Project, ProjectLspAdapterDelegate};
  55use search::{buffer_search::DivRegistrar, BufferSearchBar};
  56use settings::{update_settings_file, Settings};
  57use smol::stream::StreamExt;
  58use std::{
  59    borrow::Cow,
  60    cmp::{self, Ordering},
  61    fmt::Write,
  62    ops::Range,
  63    path::PathBuf,
  64    sync::Arc,
  65    time::Duration,
  66};
  67use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
  68use text::OffsetRangeExt;
  69use ui::TintColor;
  70use ui::{
  71    prelude::*,
  72    utils::{format_distance_from_now, DateTimeType},
  73    Avatar, AvatarShape, ButtonLike, ContextMenu, Disclosure, ElevationIndex, KeyBinding, ListItem,
  74    ListItemSpacing, PopoverMenu, PopoverMenuHandle, Tooltip,
  75};
  76use util::ResultExt;
  77use workspace::{
  78    dock::{DockPosition, Panel, PanelEvent},
  79    item::{self, FollowableItem, Item, ItemHandle},
  80    notifications::NotifyTaskExt,
  81    pane::{self, SaveIntent},
  82    searchable::{SearchEvent, SearchableItem},
  83    Pane, Save, ToggleZoom, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
  84};
  85use workspace::{searchable::SearchableItemHandle, NewFile};
  86
  87pub fn init(cx: &mut AppContext) {
  88    workspace::FollowableViewRegistry::register::<ContextEditor>(cx);
  89    cx.observe_new_views(
  90        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  91            workspace
  92                .register_action(|workspace, _: &ToggleFocus, cx| {
  93                    let settings = AssistantSettings::get_global(cx);
  94                    if !settings.enabled {
  95                        return;
  96                    }
  97
  98                    workspace.toggle_panel_focus::<AssistantPanel>(cx);
  99                })
 100                .register_action(AssistantPanel::inline_assist)
 101                .register_action(ContextEditor::quote_selection)
 102                .register_action(ContextEditor::insert_selection)
 103                .register_action(AssistantPanel::show_configuration);
 104        },
 105    )
 106    .detach();
 107
 108    cx.observe_new_views(
 109        |terminal_panel: &mut TerminalPanel, cx: &mut ViewContext<TerminalPanel>| {
 110            let settings = AssistantSettings::get_global(cx);
 111            if !settings.enabled {
 112                return;
 113            }
 114
 115            terminal_panel.register_tab_bar_button(cx.new_view(|_| InlineAssistTabBarButton), cx);
 116        },
 117    )
 118    .detach();
 119}
 120
 121struct InlineAssistTabBarButton;
 122
 123impl Render for InlineAssistTabBarButton {
 124    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 125        IconButton::new("terminal_inline_assistant", IconName::MagicWand)
 126            .icon_size(IconSize::Small)
 127            .on_click(cx.listener(|_, _, cx| {
 128                cx.dispatch_action(InlineAssist::default().boxed_clone());
 129            }))
 130            .tooltip(move |cx| Tooltip::for_action("Inline Assist", &InlineAssist::default(), cx))
 131    }
 132}
 133
 134pub enum AssistantPanelEvent {
 135    ContextEdited,
 136}
 137
 138pub struct AssistantPanel {
 139    pane: View<Pane>,
 140    workspace: WeakView<Workspace>,
 141    width: Option<Pixels>,
 142    height: Option<Pixels>,
 143    project: Model<Project>,
 144    context_store: Model<ContextStore>,
 145    languages: Arc<LanguageRegistry>,
 146    fs: Arc<dyn Fs>,
 147    subscriptions: Vec<Subscription>,
 148    model_selector_menu_handle: PopoverMenuHandle<ContextMenu>,
 149    model_summary_editor: View<Editor>,
 150    authenticate_provider_task: Option<(LanguageModelProviderId, Task<()>)>,
 151    configuration_subscription: Option<Subscription>,
 152    client_status: Option<client::Status>,
 153    watch_client_status: Option<Task<()>>,
 154    show_zed_ai_notice: bool,
 155}
 156
 157#[derive(Clone)]
 158enum ContextMetadata {
 159    Remote(RemoteContextMetadata),
 160    Saved(SavedContextMetadata),
 161}
 162
 163struct SavedContextPickerDelegate {
 164    store: Model<ContextStore>,
 165    project: Model<Project>,
 166    matches: Vec<ContextMetadata>,
 167    selected_index: usize,
 168}
 169
 170enum SavedContextPickerEvent {
 171    Confirmed(ContextMetadata),
 172}
 173
 174enum InlineAssistTarget {
 175    Editor(View<Editor>, bool),
 176    Terminal(View<TerminalView>),
 177}
 178
 179impl EventEmitter<SavedContextPickerEvent> for Picker<SavedContextPickerDelegate> {}
 180
 181impl SavedContextPickerDelegate {
 182    fn new(project: Model<Project>, store: Model<ContextStore>) -> Self {
 183        Self {
 184            project,
 185            store,
 186            matches: Vec::new(),
 187            selected_index: 0,
 188        }
 189    }
 190}
 191
 192impl PickerDelegate for SavedContextPickerDelegate {
 193    type ListItem = ListItem;
 194
 195    fn match_count(&self) -> usize {
 196        self.matches.len()
 197    }
 198
 199    fn selected_index(&self) -> usize {
 200        self.selected_index
 201    }
 202
 203    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
 204        self.selected_index = ix;
 205    }
 206
 207    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
 208        "Search...".into()
 209    }
 210
 211    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
 212        let search = self.store.read(cx).search(query, cx);
 213        cx.spawn(|this, mut cx| async move {
 214            let matches = search.await;
 215            this.update(&mut cx, |this, cx| {
 216                let host_contexts = this.delegate.store.read(cx).host_contexts();
 217                this.delegate.matches = host_contexts
 218                    .iter()
 219                    .cloned()
 220                    .map(ContextMetadata::Remote)
 221                    .chain(matches.into_iter().map(ContextMetadata::Saved))
 222                    .collect();
 223                this.delegate.selected_index = 0;
 224                cx.notify();
 225            })
 226            .ok();
 227        })
 228    }
 229
 230    fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
 231        if let Some(metadata) = self.matches.get(self.selected_index) {
 232            cx.emit(SavedContextPickerEvent::Confirmed(metadata.clone()));
 233        }
 234    }
 235
 236    fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
 237
 238    fn render_match(
 239        &self,
 240        ix: usize,
 241        selected: bool,
 242        cx: &mut ViewContext<Picker<Self>>,
 243    ) -> Option<Self::ListItem> {
 244        let context = self.matches.get(ix)?;
 245        let item = match context {
 246            ContextMetadata::Remote(context) => {
 247                let host_user = self.project.read(cx).host().and_then(|collaborator| {
 248                    self.project
 249                        .read(cx)
 250                        .user_store()
 251                        .read(cx)
 252                        .get_cached_user(collaborator.user_id)
 253                });
 254                div()
 255                    .flex()
 256                    .w_full()
 257                    .justify_between()
 258                    .gap_2()
 259                    .child(
 260                        h_flex().flex_1().overflow_x_hidden().child(
 261                            Label::new(context.summary.clone().unwrap_or(DEFAULT_TAB_TITLE.into()))
 262                                .size(LabelSize::Small),
 263                        ),
 264                    )
 265                    .child(
 266                        h_flex()
 267                            .gap_2()
 268                            .children(if let Some(host_user) = host_user {
 269                                vec![
 270                                    Avatar::new(host_user.avatar_uri.clone())
 271                                        .shape(AvatarShape::Circle)
 272                                        .into_any_element(),
 273                                    Label::new(format!("Shared by @{}", host_user.github_login))
 274                                        .color(Color::Muted)
 275                                        .size(LabelSize::Small)
 276                                        .into_any_element(),
 277                                ]
 278                            } else {
 279                                vec![Label::new("Shared by host")
 280                                    .color(Color::Muted)
 281                                    .size(LabelSize::Small)
 282                                    .into_any_element()]
 283                            }),
 284                    )
 285            }
 286            ContextMetadata::Saved(context) => div()
 287                .flex()
 288                .w_full()
 289                .justify_between()
 290                .gap_2()
 291                .child(
 292                    h_flex()
 293                        .flex_1()
 294                        .child(Label::new(context.title.clone()).size(LabelSize::Small))
 295                        .overflow_x_hidden(),
 296                )
 297                .child(
 298                    Label::new(format_distance_from_now(
 299                        DateTimeType::Local(context.mtime),
 300                        false,
 301                        true,
 302                        true,
 303                    ))
 304                    .color(Color::Muted)
 305                    .size(LabelSize::Small),
 306                ),
 307        };
 308        Some(
 309            ListItem::new(ix)
 310                .inset(true)
 311                .spacing(ListItemSpacing::Sparse)
 312                .selected(selected)
 313                .child(item),
 314        )
 315    }
 316}
 317
 318impl AssistantPanel {
 319    pub fn load(
 320        workspace: WeakView<Workspace>,
 321        prompt_builder: Arc<PromptBuilder>,
 322        cx: AsyncWindowContext,
 323    ) -> Task<Result<View<Self>>> {
 324        cx.spawn(|mut cx| async move {
 325            let context_store = workspace
 326                .update(&mut cx, |workspace, cx| {
 327                    let project = workspace.project().clone();
 328                    ContextStore::new(project, prompt_builder.clone(), cx)
 329                })?
 330                .await?;
 331
 332            workspace.update(&mut cx, |workspace, cx| {
 333                // TODO: deserialize state.
 334                cx.new_view(|cx| Self::new(workspace, context_store, cx))
 335            })
 336        })
 337    }
 338
 339    fn new(
 340        workspace: &Workspace,
 341        context_store: Model<ContextStore>,
 342        cx: &mut ViewContext<Self>,
 343    ) -> Self {
 344        let model_selector_menu_handle = PopoverMenuHandle::default();
 345        let model_summary_editor = cx.new_view(|cx| Editor::single_line(cx));
 346        let context_editor_toolbar = cx.new_view(|_| {
 347            ContextEditorToolbarItem::new(
 348                workspace,
 349                model_selector_menu_handle.clone(),
 350                model_summary_editor.clone(),
 351            )
 352        });
 353        let pane = cx.new_view(|cx| {
 354            let mut pane = Pane::new(
 355                workspace.weak_handle(),
 356                workspace.project().clone(),
 357                Default::default(),
 358                None,
 359                NewFile.boxed_clone(),
 360                cx,
 361            );
 362            pane.set_can_split(false, cx);
 363            pane.set_can_navigate(true, cx);
 364            pane.display_nav_history_buttons(None);
 365            pane.set_should_display_tab_bar(|_| true);
 366            pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
 367                let focus_handle = pane.focus_handle(cx);
 368                let left_children = IconButton::new("history", IconName::HistoryRerun)
 369                    .icon_size(IconSize::Small)
 370                    .on_click(cx.listener({
 371                        let focus_handle = focus_handle.clone();
 372                        move |_, _, cx| {
 373                            focus_handle.focus(cx);
 374                            cx.dispatch_action(DeployHistory.boxed_clone())
 375                        }
 376                    }))
 377                    .tooltip(move |cx| {
 378                        cx.new_view(|cx| {
 379                            let keybind =
 380                                KeyBinding::for_action_in(&DeployHistory, &focus_handle, cx);
 381                            Tooltip::new("Open History").key_binding(keybind)
 382                        })
 383                        .into()
 384                    })
 385                    .selected(
 386                        pane.active_item()
 387                            .map_or(false, |item| item.downcast::<ContextHistory>().is_some()),
 388                    );
 389                let right_children = h_flex()
 390                    .gap(Spacing::Small.rems(cx))
 391                    .child(
 392                        IconButton::new("new-context", IconName::Plus)
 393                            .on_click(
 394                                cx.listener(|_, _, cx| cx.dispatch_action(NewFile.boxed_clone())),
 395                            )
 396                            .tooltip(|cx| Tooltip::for_action("New Context", &NewFile, cx)),
 397                    )
 398                    .child(
 399                        IconButton::new("menu", IconName::Menu)
 400                            .icon_size(IconSize::Small)
 401                            .on_click(cx.listener(|pane, _, cx| {
 402                                let zoom_label = if pane.is_zoomed() {
 403                                    "Zoom Out"
 404                                } else {
 405                                    "Zoom In"
 406                                };
 407                                let weak_pane = cx.view().downgrade();
 408                                let menu = ContextMenu::build(cx, |menu, cx| {
 409                                    let menu = menu
 410                                        .context(pane.focus_handle(cx))
 411                                        .action("New Context", Box::new(NewFile))
 412                                        .action("History", Box::new(DeployHistory))
 413                                        .action("Prompt Library", Box::new(DeployPromptLibrary))
 414                                        .action("Configure", Box::new(ShowConfiguration))
 415                                        .action(zoom_label, Box::new(ToggleZoom));
 416
 417                                    if let Some(editor) = pane
 418                                        .active_item()
 419                                        .and_then(|e| e.downcast::<ContextEditor>())
 420                                    {
 421                                        let is_enabled = editor.read(cx).debug_inspector.is_some();
 422                                        menu.separator().toggleable_entry(
 423                                            "Debug Workflows",
 424                                            is_enabled,
 425                                            IconPosition::End,
 426                                            None,
 427                                            move |cx| {
 428                                                weak_pane
 429                                                    .update(cx, |this, cx| {
 430                                                        if let Some(context_editor) =
 431                                                            this.active_item().and_then(|item| {
 432                                                                item.downcast::<ContextEditor>()
 433                                                            })
 434                                                        {
 435                                                            context_editor.update(cx, |this, cx| {
 436                                                                if let Some(mut state) =
 437                                                                    this.debug_inspector.take()
 438                                                                {
 439                                                                    state.deactivate(cx);
 440                                                                } else {
 441                                                                    this.debug_inspector = Some(
 442                                                                        ContextInspector::new(
 443                                                                            this.editor.clone(),
 444                                                                            this.context.clone(),
 445                                                                        ),
 446                                                                    );
 447                                                                }
 448                                                            })
 449                                                        }
 450                                                    })
 451                                                    .ok();
 452                                            },
 453                                        )
 454                                    } else {
 455                                        menu
 456                                    }
 457                                });
 458                                cx.subscribe(&menu, |pane, _, _: &DismissEvent, _| {
 459                                    pane.new_item_menu = None;
 460                                })
 461                                .detach();
 462                                pane.new_item_menu = Some(menu);
 463                            })),
 464                    )
 465                    .when_some(pane.new_item_menu.as_ref(), |el, new_item_menu| {
 466                        el.child(Pane::render_menu_overlay(new_item_menu))
 467                    })
 468                    .into_any_element()
 469                    .into();
 470
 471                (Some(left_children.into_any_element()), right_children)
 472            });
 473            pane.toolbar().update(cx, |toolbar, cx| {
 474                toolbar.add_item(context_editor_toolbar.clone(), cx);
 475                toolbar.add_item(cx.new_view(BufferSearchBar::new), cx)
 476            });
 477            pane
 478        });
 479
 480        let subscriptions = vec![
 481            cx.observe(&pane, |_, _, cx| cx.notify()),
 482            cx.subscribe(&pane, Self::handle_pane_event),
 483            cx.subscribe(&context_editor_toolbar, Self::handle_toolbar_event),
 484            cx.subscribe(&model_summary_editor, Self::handle_summary_editor_event),
 485            cx.subscribe(&context_store, Self::handle_context_store_event),
 486            cx.subscribe(
 487                &LanguageModelRegistry::global(cx),
 488                |this, _, event: &language_model::Event, cx| match event {
 489                    language_model::Event::ActiveModelChanged => {
 490                        this.completion_provider_changed(cx);
 491                    }
 492                    language_model::Event::ProviderStateChanged => {
 493                        this.ensure_authenticated(cx);
 494                        cx.notify()
 495                    }
 496                    language_model::Event::AddedProvider(_)
 497                    | language_model::Event::RemovedProvider(_) => {
 498                        this.ensure_authenticated(cx);
 499                    }
 500                },
 501            ),
 502        ];
 503
 504        let watch_client_status = Self::watch_client_status(workspace.client().clone(), cx);
 505
 506        let mut this = Self {
 507            pane,
 508            workspace: workspace.weak_handle(),
 509            width: None,
 510            height: None,
 511            project: workspace.project().clone(),
 512            context_store,
 513            languages: workspace.app_state().languages.clone(),
 514            fs: workspace.app_state().fs.clone(),
 515            subscriptions,
 516            model_selector_menu_handle,
 517            model_summary_editor,
 518            authenticate_provider_task: None,
 519            configuration_subscription: None,
 520            client_status: None,
 521            watch_client_status: Some(watch_client_status),
 522            show_zed_ai_notice: false,
 523        };
 524        this.new_context(cx);
 525        this
 526    }
 527
 528    fn watch_client_status(client: Arc<Client>, cx: &mut ViewContext<Self>) -> Task<()> {
 529        let mut status_rx = client.status();
 530
 531        cx.spawn(|this, mut cx| async move {
 532            while let Some(status) = status_rx.next().await {
 533                this.update(&mut cx, |this, cx| {
 534                    if this.client_status.is_none()
 535                        || this
 536                            .client_status
 537                            .map_or(false, |old_status| old_status != status)
 538                    {
 539                        this.update_zed_ai_notice_visibility(status, cx);
 540                    }
 541                    this.client_status = Some(status);
 542                })
 543                .log_err();
 544            }
 545            this.update(&mut cx, |this, _cx| this.watch_client_status = None)
 546                .log_err();
 547        })
 548    }
 549
 550    fn handle_pane_event(
 551        &mut self,
 552        pane: View<Pane>,
 553        event: &pane::Event,
 554        cx: &mut ViewContext<Self>,
 555    ) {
 556        let update_model_summary = match event {
 557            pane::Event::Remove => {
 558                cx.emit(PanelEvent::Close);
 559                false
 560            }
 561            pane::Event::ZoomIn => {
 562                cx.emit(PanelEvent::ZoomIn);
 563                false
 564            }
 565            pane::Event::ZoomOut => {
 566                cx.emit(PanelEvent::ZoomOut);
 567                false
 568            }
 569
 570            pane::Event::AddItem { item } => {
 571                self.workspace
 572                    .update(cx, |workspace, cx| {
 573                        item.added_to_pane(workspace, self.pane.clone(), cx)
 574                    })
 575                    .ok();
 576                true
 577            }
 578
 579            pane::Event::ActivateItem { local } => {
 580                if *local {
 581                    self.workspace
 582                        .update(cx, |workspace, cx| {
 583                            workspace.unfollow_in_pane(&pane, cx);
 584                        })
 585                        .ok();
 586                }
 587                cx.emit(AssistantPanelEvent::ContextEdited);
 588                true
 589            }
 590
 591            pane::Event::RemoveItem { idx } => {
 592                if self
 593                    .pane
 594                    .read(cx)
 595                    .item_for_index(*idx)
 596                    .map_or(false, |item| item.downcast::<ConfigurationView>().is_some())
 597                {
 598                    self.configuration_subscription = None;
 599                }
 600                false
 601            }
 602            pane::Event::RemovedItem { .. } => {
 603                cx.emit(AssistantPanelEvent::ContextEdited);
 604                true
 605            }
 606
 607            _ => false,
 608        };
 609
 610        if update_model_summary {
 611            if let Some(editor) = self.active_context_editor(cx) {
 612                self.show_updated_summary(&editor, cx)
 613            }
 614        }
 615    }
 616
 617    fn handle_summary_editor_event(
 618        &mut self,
 619        model_summary_editor: View<Editor>,
 620        event: &EditorEvent,
 621        cx: &mut ViewContext<Self>,
 622    ) {
 623        if matches!(event, EditorEvent::Edited { .. }) {
 624            if let Some(context_editor) = self.active_context_editor(cx) {
 625                let new_summary = model_summary_editor.read(cx).text(cx);
 626                context_editor.update(cx, |context_editor, cx| {
 627                    context_editor.context.update(cx, |context, cx| {
 628                        if context.summary().is_none()
 629                            && (new_summary == DEFAULT_TAB_TITLE || new_summary.trim().is_empty())
 630                        {
 631                            return;
 632                        }
 633                        context.custom_summary(new_summary, cx)
 634                    });
 635                });
 636            }
 637        }
 638    }
 639
 640    fn update_zed_ai_notice_visibility(
 641        &mut self,
 642        client_status: Status,
 643        cx: &mut ViewContext<Self>,
 644    ) {
 645        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
 646
 647        // If we're signed out and don't have a provider configured, or we're signed-out AND Zed.dev is
 648        // the provider, we want to show a nudge to sign in.
 649        let show_zed_ai_notice = client_status.is_signed_out()
 650            && active_provider.map_or(true, |provider| provider.id().0 == PROVIDER_ID);
 651
 652        self.show_zed_ai_notice = show_zed_ai_notice;
 653        cx.notify();
 654    }
 655
 656    fn handle_toolbar_event(
 657        &mut self,
 658        _: View<ContextEditorToolbarItem>,
 659        _: &ContextEditorToolbarItemEvent,
 660        cx: &mut ViewContext<Self>,
 661    ) {
 662        if let Some(context_editor) = self.active_context_editor(cx) {
 663            context_editor.update(cx, |context_editor, cx| {
 664                context_editor.context.update(cx, |context, cx| {
 665                    context.summarize(true, cx);
 666                })
 667            })
 668        }
 669    }
 670
 671    fn handle_context_store_event(
 672        &mut self,
 673        _context_store: Model<ContextStore>,
 674        event: &ContextStoreEvent,
 675        cx: &mut ViewContext<Self>,
 676    ) {
 677        let ContextStoreEvent::ContextCreated(context_id) = event;
 678        let Some(context) = self
 679            .context_store
 680            .read(cx)
 681            .loaded_context_for_id(&context_id, cx)
 682        else {
 683            log::error!("no context found with ID: {}", context_id.to_proto());
 684            return;
 685        };
 686        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx).log_err();
 687
 688        let assistant_panel = cx.view().downgrade();
 689        let editor = cx.new_view(|cx| {
 690            let mut editor = ContextEditor::for_context(
 691                context,
 692                self.fs.clone(),
 693                self.workspace.clone(),
 694                self.project.clone(),
 695                lsp_adapter_delegate,
 696                assistant_panel,
 697                cx,
 698            );
 699            editor.insert_default_prompt(cx);
 700            editor
 701        });
 702
 703        self.show_context(editor.clone(), cx);
 704    }
 705
 706    fn completion_provider_changed(&mut self, cx: &mut ViewContext<Self>) {
 707        if let Some(editor) = self.active_context_editor(cx) {
 708            editor.update(cx, |active_context, cx| {
 709                active_context
 710                    .context
 711                    .update(cx, |context, cx| context.completion_provider_changed(cx))
 712            })
 713        }
 714
 715        let Some(new_provider_id) = LanguageModelRegistry::read_global(cx)
 716            .active_provider()
 717            .map(|p| p.id())
 718        else {
 719            return;
 720        };
 721
 722        if self
 723            .authenticate_provider_task
 724            .as_ref()
 725            .map_or(true, |(old_provider_id, _)| {
 726                *old_provider_id != new_provider_id
 727            })
 728        {
 729            self.authenticate_provider_task = None;
 730            self.ensure_authenticated(cx);
 731        }
 732
 733        if let Some(status) = self.client_status {
 734            self.update_zed_ai_notice_visibility(status, cx);
 735        }
 736    }
 737
 738    fn ensure_authenticated(&mut self, cx: &mut ViewContext<Self>) {
 739        if self.is_authenticated(cx) {
 740            return;
 741        }
 742
 743        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
 744            return;
 745        };
 746
 747        let load_credentials = self.authenticate(cx);
 748
 749        if self.authenticate_provider_task.is_none() {
 750            self.authenticate_provider_task = Some((
 751                provider.id(),
 752                cx.spawn(|this, mut cx| async move {
 753                    let _ = load_credentials.await;
 754                    this.update(&mut cx, |this, _cx| {
 755                        this.authenticate_provider_task = None;
 756                    })
 757                    .log_err();
 758                }),
 759            ));
 760        }
 761    }
 762
 763    pub fn inline_assist(
 764        workspace: &mut Workspace,
 765        action: &InlineAssist,
 766        cx: &mut ViewContext<Workspace>,
 767    ) {
 768        let settings = AssistantSettings::get_global(cx);
 769        if !settings.enabled {
 770            return;
 771        }
 772
 773        let Some(assistant_panel) = workspace.panel::<AssistantPanel>(cx) else {
 774            return;
 775        };
 776
 777        let Some(inline_assist_target) =
 778            Self::resolve_inline_assist_target(workspace, &assistant_panel, cx)
 779        else {
 780            return;
 781        };
 782
 783        let initial_prompt = action.prompt.clone();
 784        if assistant_panel.update(cx, |assistant, cx| assistant.is_authenticated(cx)) {
 785            match inline_assist_target {
 786                InlineAssistTarget::Editor(active_editor, include_context) => {
 787                    InlineAssistant::update_global(cx, |assistant, cx| {
 788                        assistant.assist(
 789                            &active_editor,
 790                            Some(cx.view().downgrade()),
 791                            include_context.then_some(&assistant_panel),
 792                            initial_prompt,
 793                            cx,
 794                        )
 795                    })
 796                }
 797                InlineAssistTarget::Terminal(active_terminal) => {
 798                    TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 799                        assistant.assist(
 800                            &active_terminal,
 801                            Some(cx.view().downgrade()),
 802                            Some(&assistant_panel),
 803                            initial_prompt,
 804                            cx,
 805                        )
 806                    })
 807                }
 808            }
 809        } else {
 810            let assistant_panel = assistant_panel.downgrade();
 811            cx.spawn(|workspace, mut cx| async move {
 812                assistant_panel
 813                    .update(&mut cx, |assistant, cx| assistant.authenticate(cx))?
 814                    .await?;
 815                if assistant_panel.update(&mut cx, |panel, cx| panel.is_authenticated(cx))? {
 816                    cx.update(|cx| match inline_assist_target {
 817                        InlineAssistTarget::Editor(active_editor, include_context) => {
 818                            let assistant_panel = if include_context {
 819                                assistant_panel.upgrade()
 820                            } else {
 821                                None
 822                            };
 823                            InlineAssistant::update_global(cx, |assistant, cx| {
 824                                assistant.assist(
 825                                    &active_editor,
 826                                    Some(workspace),
 827                                    assistant_panel.as_ref(),
 828                                    initial_prompt,
 829                                    cx,
 830                                )
 831                            })
 832                        }
 833                        InlineAssistTarget::Terminal(active_terminal) => {
 834                            TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 835                                assistant.assist(
 836                                    &active_terminal,
 837                                    Some(workspace),
 838                                    assistant_panel.upgrade().as_ref(),
 839                                    initial_prompt,
 840                                    cx,
 841                                )
 842                            })
 843                        }
 844                    })?
 845                } else {
 846                    workspace.update(&mut cx, |workspace, cx| {
 847                        workspace.focus_panel::<AssistantPanel>(cx)
 848                    })?;
 849                }
 850
 851                anyhow::Ok(())
 852            })
 853            .detach_and_log_err(cx)
 854        }
 855    }
 856
 857    fn resolve_inline_assist_target(
 858        workspace: &mut Workspace,
 859        assistant_panel: &View<AssistantPanel>,
 860        cx: &mut WindowContext,
 861    ) -> Option<InlineAssistTarget> {
 862        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
 863            if terminal_panel
 864                .read(cx)
 865                .focus_handle(cx)
 866                .contains_focused(cx)
 867            {
 868                if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
 869                    pane.read(cx)
 870                        .active_item()
 871                        .and_then(|t| t.downcast::<TerminalView>())
 872                }) {
 873                    return Some(InlineAssistTarget::Terminal(terminal_view));
 874                }
 875            }
 876        }
 877        let context_editor =
 878            assistant_panel
 879                .read(cx)
 880                .active_context_editor(cx)
 881                .and_then(|editor| {
 882                    let editor = &editor.read(cx).editor;
 883                    if editor.read(cx).is_focused(cx) {
 884                        Some(editor.clone())
 885                    } else {
 886                        None
 887                    }
 888                });
 889
 890        if let Some(context_editor) = context_editor {
 891            Some(InlineAssistTarget::Editor(context_editor, false))
 892        } else if let Some(workspace_editor) = workspace
 893            .active_item(cx)
 894            .and_then(|item| item.act_as::<Editor>(cx))
 895        {
 896            Some(InlineAssistTarget::Editor(workspace_editor, true))
 897        } else if let Some(terminal_view) = workspace
 898            .active_item(cx)
 899            .and_then(|item| item.act_as::<TerminalView>(cx))
 900        {
 901            Some(InlineAssistTarget::Terminal(terminal_view))
 902        } else {
 903            None
 904        }
 905    }
 906
 907    fn new_context(&mut self, cx: &mut ViewContext<Self>) -> Option<View<ContextEditor>> {
 908        if self.project.read(cx).is_remote() {
 909            let task = self
 910                .context_store
 911                .update(cx, |store, cx| store.create_remote_context(cx));
 912
 913            cx.spawn(|this, mut cx| async move {
 914                let context = task.await?;
 915
 916                this.update(&mut cx, |this, cx| {
 917                    let workspace = this.workspace.clone();
 918                    let project = this.project.clone();
 919                    let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err();
 920
 921                    let fs = this.fs.clone();
 922                    let project = this.project.clone();
 923                    let weak_assistant_panel = cx.view().downgrade();
 924
 925                    let editor = cx.new_view(|cx| {
 926                        ContextEditor::for_context(
 927                            context,
 928                            fs,
 929                            workspace,
 930                            project,
 931                            lsp_adapter_delegate,
 932                            weak_assistant_panel,
 933                            cx,
 934                        )
 935                    });
 936
 937                    this.show_context(editor, cx);
 938
 939                    anyhow::Ok(())
 940                })??;
 941
 942                anyhow::Ok(())
 943            })
 944            .detach_and_log_err(cx);
 945
 946            None
 947        } else {
 948            let context = self.context_store.update(cx, |store, cx| store.create(cx));
 949            let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx).log_err();
 950
 951            let assistant_panel = cx.view().downgrade();
 952            let editor = cx.new_view(|cx| {
 953                let mut editor = ContextEditor::for_context(
 954                    context,
 955                    self.fs.clone(),
 956                    self.workspace.clone(),
 957                    self.project.clone(),
 958                    lsp_adapter_delegate,
 959                    assistant_panel,
 960                    cx,
 961                );
 962                editor.insert_default_prompt(cx);
 963                editor
 964            });
 965
 966            self.show_context(editor.clone(), cx);
 967            Some(editor)
 968        }
 969    }
 970
 971    fn show_context(&mut self, context_editor: View<ContextEditor>, cx: &mut ViewContext<Self>) {
 972        let focus = self.focus_handle(cx).contains_focused(cx);
 973        let prev_len = self.pane.read(cx).items_len();
 974        self.pane.update(cx, |pane, cx| {
 975            pane.add_item(Box::new(context_editor.clone()), focus, focus, None, cx)
 976        });
 977
 978        if prev_len != self.pane.read(cx).items_len() {
 979            self.subscriptions
 980                .push(cx.subscribe(&context_editor, Self::handle_context_editor_event));
 981        }
 982
 983        self.show_updated_summary(&context_editor, cx);
 984
 985        cx.emit(AssistantPanelEvent::ContextEdited);
 986        cx.notify();
 987    }
 988
 989    fn show_updated_summary(
 990        &self,
 991        context_editor: &View<ContextEditor>,
 992        cx: &mut ViewContext<Self>,
 993    ) {
 994        context_editor.update(cx, |context_editor, cx| {
 995            let new_summary = context_editor.title(cx).to_string();
 996            self.model_summary_editor.update(cx, |summary_editor, cx| {
 997                if summary_editor.text(cx) != new_summary {
 998                    summary_editor.set_text(new_summary, cx);
 999                }
1000            });
1001        });
1002    }
1003
1004    fn handle_context_editor_event(
1005        &mut self,
1006        context_editor: View<ContextEditor>,
1007        event: &EditorEvent,
1008        cx: &mut ViewContext<Self>,
1009    ) {
1010        match event {
1011            EditorEvent::TitleChanged => {
1012                self.show_updated_summary(&context_editor, cx);
1013                cx.notify()
1014            }
1015            EditorEvent::Edited { .. } => cx.emit(AssistantPanelEvent::ContextEdited),
1016            _ => {}
1017        }
1018    }
1019
1020    fn show_configuration(
1021        workspace: &mut Workspace,
1022        _: &ShowConfiguration,
1023        cx: &mut ViewContext<Workspace>,
1024    ) {
1025        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1026            return;
1027        };
1028
1029        if !panel.focus_handle(cx).contains_focused(cx) {
1030            workspace.toggle_panel_focus::<AssistantPanel>(cx);
1031        }
1032
1033        panel.update(cx, |this, cx| {
1034            this.show_configuration_tab(cx);
1035        })
1036    }
1037
1038    fn show_configuration_tab(&mut self, cx: &mut ViewContext<Self>) {
1039        let configuration_item_ix = self
1040            .pane
1041            .read(cx)
1042            .items()
1043            .position(|item| item.downcast::<ConfigurationView>().is_some());
1044
1045        if let Some(configuration_item_ix) = configuration_item_ix {
1046            self.pane.update(cx, |pane, cx| {
1047                pane.activate_item(configuration_item_ix, true, true, cx);
1048            });
1049        } else {
1050            let configuration = cx.new_view(|cx| ConfigurationView::new(cx));
1051            self.configuration_subscription = Some(cx.subscribe(
1052                &configuration,
1053                |this, _, event: &ConfigurationViewEvent, cx| match event {
1054                    ConfigurationViewEvent::NewProviderContextEditor(provider) => {
1055                        if LanguageModelRegistry::read_global(cx)
1056                            .active_provider()
1057                            .map_or(true, |p| p.id() != provider.id())
1058                        {
1059                            if let Some(model) = provider.provided_models(cx).first().cloned() {
1060                                update_settings_file::<AssistantSettings>(
1061                                    this.fs.clone(),
1062                                    cx,
1063                                    move |settings, _| settings.set_model(model),
1064                                );
1065                            }
1066                        }
1067
1068                        this.new_context(cx);
1069                    }
1070                },
1071            ));
1072            self.pane.update(cx, |pane, cx| {
1073                pane.add_item(Box::new(configuration), true, true, None, cx);
1074            });
1075        }
1076    }
1077
1078    fn deploy_history(&mut self, _: &DeployHistory, cx: &mut ViewContext<Self>) {
1079        let history_item_ix = self
1080            .pane
1081            .read(cx)
1082            .items()
1083            .position(|item| item.downcast::<ContextHistory>().is_some());
1084
1085        if let Some(history_item_ix) = history_item_ix {
1086            self.pane.update(cx, |pane, cx| {
1087                pane.activate_item(history_item_ix, true, true, cx);
1088            });
1089        } else {
1090            let assistant_panel = cx.view().downgrade();
1091            let history = cx.new_view(|cx| {
1092                ContextHistory::new(
1093                    self.project.clone(),
1094                    self.context_store.clone(),
1095                    assistant_panel,
1096                    cx,
1097                )
1098            });
1099            self.pane.update(cx, |pane, cx| {
1100                pane.add_item(Box::new(history), true, true, None, cx);
1101            });
1102        }
1103    }
1104
1105    fn deploy_prompt_library(&mut self, _: &DeployPromptLibrary, cx: &mut ViewContext<Self>) {
1106        open_prompt_library(self.languages.clone(), cx).detach_and_log_err(cx);
1107    }
1108
1109    fn toggle_model_selector(&mut self, _: &ToggleModelSelector, cx: &mut ViewContext<Self>) {
1110        self.model_selector_menu_handle.toggle(cx);
1111    }
1112
1113    fn active_context_editor(&self, cx: &AppContext) -> Option<View<ContextEditor>> {
1114        self.pane
1115            .read(cx)
1116            .active_item()?
1117            .downcast::<ContextEditor>()
1118    }
1119
1120    pub fn active_context(&self, cx: &AppContext) -> Option<Model<Context>> {
1121        Some(self.active_context_editor(cx)?.read(cx).context.clone())
1122    }
1123
1124    fn open_saved_context(
1125        &mut self,
1126        path: PathBuf,
1127        cx: &mut ViewContext<Self>,
1128    ) -> Task<Result<()>> {
1129        let existing_context = self.pane.read(cx).items().find_map(|item| {
1130            item.downcast::<ContextEditor>()
1131                .filter(|editor| editor.read(cx).context.read(cx).path() == Some(&path))
1132        });
1133        if let Some(existing_context) = existing_context {
1134            return cx.spawn(|this, mut cx| async move {
1135                this.update(&mut cx, |this, cx| this.show_context(existing_context, cx))
1136            });
1137        }
1138
1139        let context = self
1140            .context_store
1141            .update(cx, |store, cx| store.open_local_context(path.clone(), cx));
1142        let fs = self.fs.clone();
1143        let project = self.project.clone();
1144        let workspace = self.workspace.clone();
1145
1146        let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err();
1147
1148        cx.spawn(|this, mut cx| async move {
1149            let context = context.await?;
1150            let assistant_panel = this.clone();
1151            this.update(&mut cx, |this, cx| {
1152                let editor = cx.new_view(|cx| {
1153                    ContextEditor::for_context(
1154                        context,
1155                        fs,
1156                        workspace,
1157                        project,
1158                        lsp_adapter_delegate,
1159                        assistant_panel,
1160                        cx,
1161                    )
1162                });
1163                this.show_context(editor, cx);
1164                anyhow::Ok(())
1165            })??;
1166            Ok(())
1167        })
1168    }
1169
1170    fn open_remote_context(
1171        &mut self,
1172        id: ContextId,
1173        cx: &mut ViewContext<Self>,
1174    ) -> Task<Result<View<ContextEditor>>> {
1175        let existing_context = self.pane.read(cx).items().find_map(|item| {
1176            item.downcast::<ContextEditor>()
1177                .filter(|editor| *editor.read(cx).context.read(cx).id() == id)
1178        });
1179        if let Some(existing_context) = existing_context {
1180            return cx.spawn(|this, mut cx| async move {
1181                this.update(&mut cx, |this, cx| {
1182                    this.show_context(existing_context.clone(), cx)
1183                })?;
1184                Ok(existing_context)
1185            });
1186        }
1187
1188        let context = self
1189            .context_store
1190            .update(cx, |store, cx| store.open_remote_context(id, cx));
1191        let fs = self.fs.clone();
1192        let workspace = self.workspace.clone();
1193        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx).log_err();
1194
1195        cx.spawn(|this, mut cx| async move {
1196            let context = context.await?;
1197            let assistant_panel = this.clone();
1198            this.update(&mut cx, |this, cx| {
1199                let editor = cx.new_view(|cx| {
1200                    ContextEditor::for_context(
1201                        context,
1202                        fs,
1203                        workspace,
1204                        this.project.clone(),
1205                        lsp_adapter_delegate,
1206                        assistant_panel,
1207                        cx,
1208                    )
1209                });
1210                this.show_context(editor.clone(), cx);
1211                anyhow::Ok(editor)
1212            })?
1213        })
1214    }
1215
1216    fn is_authenticated(&mut self, cx: &mut ViewContext<Self>) -> bool {
1217        LanguageModelRegistry::read_global(cx)
1218            .active_provider()
1219            .map_or(false, |provider| provider.is_authenticated(cx))
1220    }
1221
1222    fn authenticate(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
1223        LanguageModelRegistry::read_global(cx)
1224            .active_provider()
1225            .map_or(
1226                Task::ready(Err(anyhow!("no active language model provider"))),
1227                |provider| provider.authenticate(cx),
1228            )
1229    }
1230}
1231
1232impl Render for AssistantPanel {
1233    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1234        let mut registrar = DivRegistrar::new(
1235            |panel, cx| {
1236                panel
1237                    .pane
1238                    .read(cx)
1239                    .toolbar()
1240                    .read(cx)
1241                    .item_of_type::<BufferSearchBar>()
1242            },
1243            cx,
1244        );
1245        BufferSearchBar::register(&mut registrar);
1246        let registrar = registrar.into_div();
1247
1248        v_flex()
1249            .key_context("AssistantPanel")
1250            .size_full()
1251            .on_action(cx.listener(|this, _: &workspace::NewFile, cx| {
1252                this.new_context(cx);
1253            }))
1254            .on_action(
1255                cx.listener(|this, _: &ShowConfiguration, cx| this.show_configuration_tab(cx)),
1256            )
1257            .on_action(cx.listener(AssistantPanel::deploy_history))
1258            .on_action(cx.listener(AssistantPanel::deploy_prompt_library))
1259            .on_action(cx.listener(AssistantPanel::toggle_model_selector))
1260            .child(registrar.size_full().child(self.pane.clone()))
1261            .into_any_element()
1262    }
1263}
1264
1265impl Panel for AssistantPanel {
1266    fn persistent_name() -> &'static str {
1267        "AssistantPanel"
1268    }
1269
1270    fn position(&self, cx: &WindowContext) -> DockPosition {
1271        match AssistantSettings::get_global(cx).dock {
1272            AssistantDockPosition::Left => DockPosition::Left,
1273            AssistantDockPosition::Bottom => DockPosition::Bottom,
1274            AssistantDockPosition::Right => DockPosition::Right,
1275        }
1276    }
1277
1278    fn position_is_valid(&self, _: DockPosition) -> bool {
1279        true
1280    }
1281
1282    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1283        settings::update_settings_file::<AssistantSettings>(
1284            self.fs.clone(),
1285            cx,
1286            move |settings, _| {
1287                let dock = match position {
1288                    DockPosition::Left => AssistantDockPosition::Left,
1289                    DockPosition::Bottom => AssistantDockPosition::Bottom,
1290                    DockPosition::Right => AssistantDockPosition::Right,
1291                };
1292                settings.set_dock(dock);
1293            },
1294        );
1295    }
1296
1297    fn size(&self, cx: &WindowContext) -> Pixels {
1298        let settings = AssistantSettings::get_global(cx);
1299        match self.position(cx) {
1300            DockPosition::Left | DockPosition::Right => {
1301                self.width.unwrap_or(settings.default_width)
1302            }
1303            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1304        }
1305    }
1306
1307    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1308        match self.position(cx) {
1309            DockPosition::Left | DockPosition::Right => self.width = size,
1310            DockPosition::Bottom => self.height = size,
1311        }
1312        cx.notify();
1313    }
1314
1315    fn is_zoomed(&self, cx: &WindowContext) -> bool {
1316        self.pane.read(cx).is_zoomed()
1317    }
1318
1319    fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1320        self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
1321    }
1322
1323    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1324        if active {
1325            if self.pane.read(cx).items_len() == 0 {
1326                self.new_context(cx);
1327            }
1328
1329            self.ensure_authenticated(cx);
1330        }
1331    }
1332
1333    fn pane(&self) -> Option<View<Pane>> {
1334        Some(self.pane.clone())
1335    }
1336
1337    fn remote_id() -> Option<proto::PanelId> {
1338        Some(proto::PanelId::AssistantPanel)
1339    }
1340
1341    fn icon(&self, cx: &WindowContext) -> Option<IconName> {
1342        let settings = AssistantSettings::get_global(cx);
1343        if !settings.enabled || !settings.button {
1344            return None;
1345        }
1346
1347        Some(IconName::ZedAssistant)
1348    }
1349
1350    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1351        Some("Assistant Panel")
1352    }
1353
1354    fn toggle_action(&self) -> Box<dyn Action> {
1355        Box::new(ToggleFocus)
1356    }
1357}
1358
1359impl EventEmitter<PanelEvent> for AssistantPanel {}
1360impl EventEmitter<AssistantPanelEvent> for AssistantPanel {}
1361
1362impl FocusableView for AssistantPanel {
1363    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1364        self.pane.focus_handle(cx)
1365    }
1366}
1367
1368pub enum ContextEditorEvent {
1369    Edited,
1370    TabContentChanged,
1371}
1372
1373#[derive(Copy, Clone, Debug, PartialEq)]
1374struct ScrollPosition {
1375    offset_before_cursor: gpui::Point<f32>,
1376    cursor: Anchor,
1377}
1378
1379struct WorkflowStep {
1380    range: Range<language::Anchor>,
1381    header_block_id: CustomBlockId,
1382    footer_block_id: CustomBlockId,
1383    resolved_step: Option<Result<ResolvedWorkflowStep, Arc<anyhow::Error>>>,
1384    assist: Option<WorkflowAssist>,
1385}
1386
1387impl WorkflowStep {
1388    fn status(&self, cx: &AppContext) -> WorkflowStepStatus {
1389        match self.resolved_step.as_ref() {
1390            Some(Ok(_)) => {
1391                if let Some(assist) = self.assist.as_ref() {
1392                    let assistant = InlineAssistant::global(cx);
1393                    if assist
1394                        .assist_ids
1395                        .iter()
1396                        .any(|assist_id| assistant.assist_status(*assist_id, cx).is_pending())
1397                    {
1398                        WorkflowStepStatus::Pending
1399                    } else if assist
1400                        .assist_ids
1401                        .iter()
1402                        .all(|assist_id| assistant.assist_status(*assist_id, cx).is_confirmed())
1403                    {
1404                        WorkflowStepStatus::Confirmed
1405                    } else if assist
1406                        .assist_ids
1407                        .iter()
1408                        .all(|assist_id| assistant.assist_status(*assist_id, cx).is_done())
1409                    {
1410                        WorkflowStepStatus::Done
1411                    } else {
1412                        WorkflowStepStatus::Idle
1413                    }
1414                } else {
1415                    WorkflowStepStatus::Idle
1416                }
1417            }
1418            Some(Err(error)) => WorkflowStepStatus::Error(error.clone()),
1419            None => WorkflowStepStatus::Resolving,
1420        }
1421    }
1422}
1423
1424enum WorkflowStepStatus {
1425    Resolving,
1426    Error(Arc<anyhow::Error>),
1427    Idle,
1428    Pending,
1429    Done,
1430    Confirmed,
1431}
1432
1433impl WorkflowStepStatus {
1434    pub(crate) fn is_confirmed(&self) -> bool {
1435        matches!(self, Self::Confirmed)
1436    }
1437
1438    pub(crate) fn into_element(
1439        &self,
1440        step_range: Range<language::Anchor>,
1441        focus_handle: FocusHandle,
1442        editor: WeakView<ContextEditor>,
1443        cx: &mut BlockContext<'_, '_>,
1444    ) -> AnyElement {
1445        let id = EntityId::from(cx.block_id);
1446        fn display_keybind_in_tooltip(
1447            step_range: &Range<language::Anchor>,
1448            editor: &WeakView<ContextEditor>,
1449            cx: &mut WindowContext<'_>,
1450        ) -> bool {
1451            editor
1452                .update(cx, |this, _| {
1453                    this.active_workflow_step
1454                        .as_ref()
1455                        .map(|step| &step.range == step_range)
1456                })
1457                .ok()
1458                .flatten()
1459                .unwrap_or_default()
1460        }
1461        match self {
1462            WorkflowStepStatus::Resolving => Label::new("Resolving")
1463                .size(LabelSize::Small)
1464                .with_animation(
1465                    ("resolving-suggestion-animation", id),
1466                    Animation::new(Duration::from_secs(2))
1467                        .repeat()
1468                        .with_easing(pulsating_between(0.2, 1.0)),
1469                    |label, delta| label.alpha(delta),
1470                )
1471                .into_any_element(),
1472
1473            WorkflowStepStatus::Error(error) => {
1474                let error = error.clone();
1475                h_flex()
1476                    .gap_2()
1477                    .child(
1478                        div()
1479                            .id("step-resolution-failure")
1480                            .child(
1481                                Label::new("Step Resolution Failed")
1482                                    .size(LabelSize::Small)
1483                                    .color(Color::Error),
1484                            )
1485                            .tooltip(move |cx| Tooltip::text(error.to_string(), cx)),
1486                    )
1487                    .child(
1488                        Button::new(("transform", id), "Retry")
1489                            .icon(IconName::Update)
1490                            .icon_position(IconPosition::Start)
1491                            .icon_size(IconSize::Small)
1492                            .label_size(LabelSize::Small)
1493                            .on_click({
1494                                let editor = editor.clone();
1495                                let step_range = step_range.clone();
1496                                move |_, cx| {
1497                                    editor
1498                                        .update(cx, |this, cx| {
1499                                            this.resolve_workflow_step(step_range.clone(), cx)
1500                                        })
1501                                        .ok();
1502                                }
1503                            }),
1504                    )
1505                    .into_any()
1506            }
1507
1508            WorkflowStepStatus::Idle => Button::new(("transform", id), "Transform")
1509                .icon(IconName::Sparkle)
1510                .icon_position(IconPosition::Start)
1511                .icon_size(IconSize::Small)
1512                .label_size(LabelSize::Small)
1513                .style(ButtonStyle::Tinted(TintColor::Accent))
1514                .tooltip({
1515                    let step_range = step_range.clone();
1516                    let editor = editor.clone();
1517                    move |cx| {
1518                        cx.new_view(|cx| {
1519                            let tooltip = Tooltip::new("Transform");
1520                            if display_keybind_in_tooltip(&step_range, &editor, cx) {
1521                                tooltip.key_binding(KeyBinding::for_action_in(
1522                                    &Assist,
1523                                    &focus_handle,
1524                                    cx,
1525                                ))
1526                            } else {
1527                                tooltip
1528                            }
1529                        })
1530                        .into()
1531                    }
1532                })
1533                .on_click({
1534                    let editor = editor.clone();
1535                    let step_range = step_range.clone();
1536                    move |_, cx| {
1537                        editor
1538                            .update(cx, |this, cx| {
1539                                this.apply_workflow_step(step_range.clone(), cx)
1540                            })
1541                            .ok();
1542                    }
1543                })
1544                .into_any_element(),
1545            WorkflowStepStatus::Pending => h_flex()
1546                .items_center()
1547                .gap_2()
1548                .child(
1549                    Label::new("Applying...")
1550                        .size(LabelSize::Small)
1551                        .with_animation(
1552                            ("applying-step-transformation-label", id),
1553                            Animation::new(Duration::from_secs(2))
1554                                .repeat()
1555                                .with_easing(pulsating_between(0.2, 1.0)),
1556                            |label, delta| label.alpha(delta),
1557                        ),
1558                )
1559                .child(
1560                    IconButton::new(("stop-transformation", id), IconName::Stop)
1561                        .icon_size(IconSize::Small)
1562                        .style(ButtonStyle::Tinted(TintColor::Negative))
1563                        .tooltip({
1564                            let step_range = step_range.clone();
1565                            let editor = editor.clone();
1566                            move |cx| {
1567                                cx.new_view(|cx| {
1568                                    let tooltip = Tooltip::new("Stop Transformation");
1569                                    if display_keybind_in_tooltip(&step_range, &editor, cx) {
1570                                        tooltip.key_binding(KeyBinding::for_action_in(
1571                                            &editor::actions::Cancel,
1572                                            &focus_handle,
1573                                            cx,
1574                                        ))
1575                                    } else {
1576                                        tooltip
1577                                    }
1578                                })
1579                                .into()
1580                            }
1581                        })
1582                        .on_click({
1583                            let editor = editor.clone();
1584                            let step_range = step_range.clone();
1585                            move |_, cx| {
1586                                editor
1587                                    .update(cx, |this, cx| {
1588                                        this.stop_workflow_step(step_range.clone(), cx)
1589                                    })
1590                                    .ok();
1591                            }
1592                        }),
1593                )
1594                .into_any_element(),
1595            WorkflowStepStatus::Done => h_flex()
1596                .gap_1()
1597                .child(
1598                    IconButton::new(("stop-transformation", id), IconName::Close)
1599                        .icon_size(IconSize::Small)
1600                        .style(ButtonStyle::Tinted(TintColor::Negative))
1601                        .tooltip({
1602                            let focus_handle = focus_handle.clone();
1603                            let editor = editor.clone();
1604                            let step_range = step_range.clone();
1605                            move |cx| {
1606                                cx.new_view(|cx| {
1607                                    let tooltip = Tooltip::new("Reject Transformation");
1608                                    if display_keybind_in_tooltip(&step_range, &editor, cx) {
1609                                        tooltip.key_binding(KeyBinding::for_action_in(
1610                                            &editor::actions::Cancel,
1611                                            &focus_handle,
1612                                            cx,
1613                                        ))
1614                                    } else {
1615                                        tooltip
1616                                    }
1617                                })
1618                                .into()
1619                            }
1620                        })
1621                        .on_click({
1622                            let editor = editor.clone();
1623                            let step_range = step_range.clone();
1624                            move |_, cx| {
1625                                editor
1626                                    .update(cx, |this, cx| {
1627                                        this.reject_workflow_step(step_range.clone(), cx);
1628                                    })
1629                                    .ok();
1630                            }
1631                        }),
1632                )
1633                .child(
1634                    Button::new(("confirm-workflow-step", id), "Accept")
1635                        .icon(IconName::Check)
1636                        .icon_position(IconPosition::Start)
1637                        .icon_size(IconSize::Small)
1638                        .label_size(LabelSize::Small)
1639                        .style(ButtonStyle::Tinted(TintColor::Positive))
1640                        .tooltip({
1641                            let editor = editor.clone();
1642                            let step_range = step_range.clone();
1643                            move |cx| {
1644                                cx.new_view(|cx| {
1645                                    let tooltip = Tooltip::new("Accept Transformation");
1646                                    if display_keybind_in_tooltip(&step_range, &editor, cx) {
1647                                        tooltip.key_binding(KeyBinding::for_action_in(
1648                                            &Assist,
1649                                            &focus_handle,
1650                                            cx,
1651                                        ))
1652                                    } else {
1653                                        tooltip
1654                                    }
1655                                })
1656                                .into()
1657                            }
1658                        })
1659                        .on_click({
1660                            let editor = editor.clone();
1661                            let step_range = step_range.clone();
1662                            move |_, cx| {
1663                                editor
1664                                    .update(cx, |this, cx| {
1665                                        this.confirm_workflow_step(step_range.clone(), cx);
1666                                    })
1667                                    .ok();
1668                            }
1669                        }),
1670                )
1671                .into_any_element(),
1672            WorkflowStepStatus::Confirmed => h_flex()
1673                .child(
1674                    Button::new(("revert-workflow-step", id), "Undo")
1675                        .style(ButtonStyle::Filled)
1676                        .icon(Some(IconName::Undo))
1677                        .icon_position(IconPosition::Start)
1678                        .icon_size(IconSize::Small)
1679                        .label_size(LabelSize::Small)
1680                        .on_click({
1681                            let editor = editor.clone();
1682                            let step_range = step_range.clone();
1683                            move |_, cx| {
1684                                editor
1685                                    .update(cx, |this, cx| {
1686                                        this.undo_workflow_step(step_range.clone(), cx);
1687                                    })
1688                                    .ok();
1689                            }
1690                        }),
1691                )
1692                .into_any_element(),
1693        }
1694    }
1695}
1696
1697#[derive(Debug, Eq, PartialEq)]
1698struct ActiveWorkflowStep {
1699    range: Range<language::Anchor>,
1700    resolved: bool,
1701}
1702
1703struct WorkflowAssist {
1704    editor: WeakView<Editor>,
1705    editor_was_open: bool,
1706    assist_ids: Vec<InlineAssistId>,
1707    _observe_assist_status: Task<()>,
1708}
1709
1710pub struct ContextEditor {
1711    context: Model<Context>,
1712    fs: Arc<dyn Fs>,
1713    workspace: WeakView<Workspace>,
1714    project: Model<Project>,
1715    lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1716    editor: View<Editor>,
1717    blocks: HashSet<CustomBlockId>,
1718    scroll_position: Option<ScrollPosition>,
1719    remote_id: Option<workspace::ViewId>,
1720    pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
1721    pending_slash_command_blocks: HashMap<Range<language::Anchor>, CustomBlockId>,
1722    _subscriptions: Vec<Subscription>,
1723    workflow_steps: HashMap<Range<language::Anchor>, WorkflowStep>,
1724    active_workflow_step: Option<ActiveWorkflowStep>,
1725    assistant_panel: WeakView<AssistantPanel>,
1726    error_message: Option<SharedString>,
1727    debug_inspector: Option<ContextInspector>,
1728    show_accept_terms: bool,
1729}
1730
1731const DEFAULT_TAB_TITLE: &str = "New Context";
1732const MAX_TAB_TITLE_LEN: usize = 16;
1733
1734impl ContextEditor {
1735    fn for_context(
1736        context: Model<Context>,
1737        fs: Arc<dyn Fs>,
1738        workspace: WeakView<Workspace>,
1739        project: Model<Project>,
1740        lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1741        assistant_panel: WeakView<AssistantPanel>,
1742        cx: &mut ViewContext<Self>,
1743    ) -> Self {
1744        let completion_provider = SlashCommandCompletionProvider::new(
1745            Some(cx.view().downgrade()),
1746            Some(workspace.clone()),
1747        );
1748
1749        let editor = cx.new_view(|cx| {
1750            let mut editor = Editor::for_buffer(context.read(cx).buffer().clone(), None, cx);
1751            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
1752            editor.set_show_line_numbers(false, cx);
1753            editor.set_show_git_diff_gutter(false, cx);
1754            editor.set_show_code_actions(false, cx);
1755            editor.set_show_runnables(false, cx);
1756            editor.set_show_wrap_guides(false, cx);
1757            editor.set_show_indent_guides(false, cx);
1758            editor.set_completion_provider(Box::new(completion_provider));
1759            editor.set_collaboration_hub(Box::new(project.clone()));
1760            editor
1761        });
1762
1763        let _subscriptions = vec![
1764            cx.observe(&context, |_, _, cx| cx.notify()),
1765            cx.subscribe(&context, Self::handle_context_event),
1766            cx.subscribe(&editor, Self::handle_editor_event),
1767            cx.subscribe(&editor, Self::handle_editor_search_event),
1768        ];
1769
1770        let sections = context.read(cx).slash_command_output_sections().to_vec();
1771        let mut this = Self {
1772            context,
1773            editor,
1774            lsp_adapter_delegate,
1775            blocks: Default::default(),
1776            scroll_position: None,
1777            remote_id: None,
1778            fs,
1779            workspace,
1780            project,
1781            pending_slash_command_creases: HashMap::default(),
1782            pending_slash_command_blocks: HashMap::default(),
1783            _subscriptions,
1784            workflow_steps: HashMap::default(),
1785            active_workflow_step: None,
1786            assistant_panel,
1787            error_message: None,
1788            debug_inspector: None,
1789            show_accept_terms: false,
1790        };
1791        this.update_message_headers(cx);
1792        this.insert_slash_command_output_sections(sections, cx);
1793        this
1794    }
1795
1796    fn insert_default_prompt(&mut self, cx: &mut ViewContext<Self>) {
1797        let command_name = DefaultSlashCommand.name();
1798        self.editor.update(cx, |editor, cx| {
1799            editor.insert(&format!("/{command_name}"), cx)
1800        });
1801        self.split(&Split, cx);
1802        let command = self.context.update(cx, |context, cx| {
1803            let first_message_id = context.messages(cx).next().unwrap().id;
1804            context.update_metadata(first_message_id, cx, |metadata| {
1805                metadata.role = Role::System;
1806            });
1807            context.reparse_slash_commands(cx);
1808            context.pending_slash_commands()[0].clone()
1809        });
1810
1811        self.run_command(
1812            command.source_range,
1813            &command.name,
1814            command.argument.as_deref(),
1815            false,
1816            self.workspace.clone(),
1817            cx,
1818        );
1819    }
1820
1821    fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
1822        let provider = LanguageModelRegistry::read_global(cx).active_provider();
1823        if provider
1824            .as_ref()
1825            .map_or(false, |provider| provider.must_accept_terms(cx))
1826        {
1827            self.show_accept_terms = true;
1828            cx.notify();
1829            return;
1830        }
1831
1832        if !self.apply_active_workflow_step(cx) {
1833            self.error_message = None;
1834            self.send_to_model(cx);
1835            cx.notify();
1836        }
1837    }
1838
1839    fn apply_workflow_step(&mut self, range: Range<language::Anchor>, cx: &mut ViewContext<Self>) {
1840        self.show_workflow_step(range.clone(), cx);
1841
1842        if let Some(workflow_step) = self.workflow_steps.get(&range) {
1843            if let Some(assist) = workflow_step.assist.as_ref() {
1844                let assist_ids = assist.assist_ids.clone();
1845                cx.window_context().defer(|cx| {
1846                    InlineAssistant::update_global(cx, |assistant, cx| {
1847                        for assist_id in assist_ids {
1848                            assistant.start_assist(assist_id, cx);
1849                        }
1850                    })
1851                });
1852            }
1853        }
1854    }
1855
1856    fn apply_active_workflow_step(&mut self, cx: &mut ViewContext<Self>) -> bool {
1857        let Some(step) = self.active_workflow_step() else {
1858            return false;
1859        };
1860
1861        let range = step.range.clone();
1862        match step.status(cx) {
1863            WorkflowStepStatus::Resolving | WorkflowStepStatus::Pending => true,
1864            WorkflowStepStatus::Idle => {
1865                self.apply_workflow_step(range, cx);
1866                true
1867            }
1868            WorkflowStepStatus::Done => {
1869                self.confirm_workflow_step(range, cx);
1870                true
1871            }
1872            WorkflowStepStatus::Error(_) => {
1873                self.resolve_workflow_step(range, cx);
1874                true
1875            }
1876            WorkflowStepStatus::Confirmed => false,
1877        }
1878    }
1879
1880    fn resolve_workflow_step(
1881        &mut self,
1882        range: Range<language::Anchor>,
1883        cx: &mut ViewContext<Self>,
1884    ) {
1885        self.context.update(cx, |context, cx| {
1886            context.resolve_workflow_step(range, self.project.clone(), cx)
1887        });
1888    }
1889
1890    fn stop_workflow_step(&mut self, range: Range<language::Anchor>, cx: &mut ViewContext<Self>) {
1891        if let Some(workflow_step) = self.workflow_steps.get(&range) {
1892            if let Some(assist) = workflow_step.assist.as_ref() {
1893                let assist_ids = assist.assist_ids.clone();
1894                cx.window_context().defer(|cx| {
1895                    InlineAssistant::update_global(cx, |assistant, cx| {
1896                        for assist_id in assist_ids {
1897                            assistant.stop_assist(assist_id, cx);
1898                        }
1899                    })
1900                });
1901            }
1902        }
1903    }
1904
1905    fn undo_workflow_step(&mut self, range: Range<language::Anchor>, cx: &mut ViewContext<Self>) {
1906        if let Some(workflow_step) = self.workflow_steps.get_mut(&range) {
1907            if let Some(assist) = workflow_step.assist.take() {
1908                cx.window_context().defer(|cx| {
1909                    InlineAssistant::update_global(cx, |assistant, cx| {
1910                        for assist_id in assist.assist_ids {
1911                            assistant.undo_assist(assist_id, cx);
1912                        }
1913                    })
1914                });
1915            }
1916        }
1917    }
1918
1919    fn confirm_workflow_step(
1920        &mut self,
1921        range: Range<language::Anchor>,
1922        cx: &mut ViewContext<Self>,
1923    ) {
1924        if let Some(workflow_step) = self.workflow_steps.get(&range) {
1925            if let Some(assist) = workflow_step.assist.as_ref() {
1926                let assist_ids = assist.assist_ids.clone();
1927                cx.window_context().defer(move |cx| {
1928                    InlineAssistant::update_global(cx, |assistant, cx| {
1929                        for assist_id in assist_ids {
1930                            assistant.finish_assist(assist_id, false, cx);
1931                        }
1932                    })
1933                });
1934            }
1935        }
1936    }
1937
1938    fn reject_workflow_step(&mut self, range: Range<language::Anchor>, cx: &mut ViewContext<Self>) {
1939        if let Some(workflow_step) = self.workflow_steps.get_mut(&range) {
1940            if let Some(assist) = workflow_step.assist.take() {
1941                cx.window_context().defer(move |cx| {
1942                    InlineAssistant::update_global(cx, |assistant, cx| {
1943                        for assist_id in assist.assist_ids {
1944                            assistant.finish_assist(assist_id, true, cx);
1945                        }
1946                    })
1947                });
1948            }
1949        }
1950    }
1951
1952    fn send_to_model(&mut self, cx: &mut ViewContext<Self>) {
1953        if let Some(user_message) = self.context.update(cx, |context, cx| context.assist(cx)) {
1954            let new_selection = {
1955                let cursor = user_message
1956                    .start
1957                    .to_offset(self.context.read(cx).buffer().read(cx));
1958                cursor..cursor
1959            };
1960            self.editor.update(cx, |editor, cx| {
1961                editor.change_selections(
1962                    Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
1963                    cx,
1964                    |selections| selections.select_ranges([new_selection]),
1965                );
1966            });
1967            // Avoid scrolling to the new cursor position so the assistant's output is stable.
1968            cx.defer(|this, _| this.scroll_position = None);
1969        }
1970    }
1971
1972    fn cancel(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1973        if self
1974            .context
1975            .update(cx, |context, _| context.cancel_last_assist())
1976        {
1977            return;
1978        }
1979
1980        if let Some(active_step) = self.active_workflow_step() {
1981            match active_step.status(cx) {
1982                WorkflowStepStatus::Pending => {
1983                    self.stop_workflow_step(active_step.range.clone(), cx);
1984                    return;
1985                }
1986                WorkflowStepStatus::Done => {
1987                    self.reject_workflow_step(active_step.range.clone(), cx);
1988                    return;
1989                }
1990                _ => {}
1991            }
1992        }
1993        cx.propagate();
1994    }
1995
1996    fn debug_workflow_steps(&mut self, _: &DebugWorkflowSteps, cx: &mut ViewContext<Self>) {
1997        let mut output = String::new();
1998        for (i, step) in self.context.read(cx).workflow_steps().iter().enumerate() {
1999            output.push_str(&format!("Step {}:\n", i + 1));
2000            output.push_str(&format!(
2001                "Content: {}\n",
2002                self.context
2003                    .read(cx)
2004                    .buffer()
2005                    .read(cx)
2006                    .text_for_range(step.tagged_range.clone())
2007                    .collect::<String>()
2008            ));
2009            match &step.status {
2010                crate::WorkflowStepStatus::Resolved(ResolvedWorkflowStep {
2011                    title,
2012                    suggestions,
2013                }) => {
2014                    output.push_str("Resolution:\n");
2015                    output.push_str(&format!("  {:?}\n", title));
2016                    output.push_str(&format!("  {:?}\n", suggestions));
2017                }
2018                crate::WorkflowStepStatus::Pending(_) => {
2019                    output.push_str("Resolution: Pending\n");
2020                }
2021                crate::WorkflowStepStatus::Error(error) => {
2022                    writeln!(output, "Resolution: Error\n{:?}", error).unwrap();
2023                }
2024            }
2025            output.push('\n');
2026        }
2027
2028        let editor = self
2029            .workspace
2030            .update(cx, |workspace, cx| Editor::new_in_workspace(workspace, cx));
2031
2032        if let Ok(editor) = editor {
2033            cx.spawn(|_, mut cx| async move {
2034                let editor = editor.await?;
2035                editor.update(&mut cx, |editor, cx| editor.set_text(output, cx))
2036            })
2037            .detach_and_notify_err(cx);
2038        }
2039    }
2040
2041    fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
2042        let cursors = self.cursors(cx);
2043        self.context.update(cx, |context, cx| {
2044            let messages = context
2045                .messages_for_offsets(cursors, cx)
2046                .into_iter()
2047                .map(|message| message.id)
2048                .collect();
2049            context.cycle_message_roles(messages, cx)
2050        });
2051    }
2052
2053    fn cursors(&self, cx: &AppContext) -> Vec<usize> {
2054        let selections = self.editor.read(cx).selections.all::<usize>(cx);
2055        selections
2056            .into_iter()
2057            .map(|selection| selection.head())
2058            .collect()
2059    }
2060
2061    fn insert_command(&mut self, name: &str, cx: &mut ViewContext<Self>) {
2062        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
2063            self.editor.update(cx, |editor, cx| {
2064                editor.transact(cx, |editor, cx| {
2065                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel());
2066                    let snapshot = editor.buffer().read(cx).snapshot(cx);
2067                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
2068                    if newest_cursor.column > 0
2069                        || snapshot
2070                            .chars_at(newest_cursor)
2071                            .next()
2072                            .map_or(false, |ch| ch != '\n')
2073                    {
2074                        editor.move_to_end_of_line(
2075                            &MoveToEndOfLine {
2076                                stop_at_soft_wraps: false,
2077                            },
2078                            cx,
2079                        );
2080                        editor.newline(&Newline, cx);
2081                    }
2082
2083                    editor.insert(&format!("/{name}"), cx);
2084                    if command.requires_argument() {
2085                        editor.insert(" ", cx);
2086                        editor.show_completions(&ShowCompletions::default(), cx);
2087                    }
2088                });
2089            });
2090            if !command.requires_argument() {
2091                self.confirm_command(&ConfirmCommand, cx);
2092            }
2093        }
2094    }
2095
2096    pub fn confirm_command(&mut self, _: &ConfirmCommand, cx: &mut ViewContext<Self>) {
2097        let selections = self.editor.read(cx).selections.disjoint_anchors();
2098        let mut commands_by_range = HashMap::default();
2099        let workspace = self.workspace.clone();
2100        self.context.update(cx, |context, cx| {
2101            context.reparse_slash_commands(cx);
2102            for selection in selections.iter() {
2103                if let Some(command) =
2104                    context.pending_command_for_position(selection.head().text_anchor, cx)
2105                {
2106                    commands_by_range
2107                        .entry(command.source_range.clone())
2108                        .or_insert_with(|| command.clone());
2109                }
2110            }
2111        });
2112
2113        if commands_by_range.is_empty() {
2114            cx.propagate();
2115        } else {
2116            for command in commands_by_range.into_values() {
2117                self.run_command(
2118                    command.source_range,
2119                    &command.name,
2120                    command.argument.as_deref(),
2121                    true,
2122                    workspace.clone(),
2123                    cx,
2124                );
2125            }
2126            cx.stop_propagation();
2127        }
2128    }
2129
2130    pub fn run_command(
2131        &mut self,
2132        command_range: Range<language::Anchor>,
2133        name: &str,
2134        argument: Option<&str>,
2135        insert_trailing_newline: bool,
2136        workspace: WeakView<Workspace>,
2137        cx: &mut ViewContext<Self>,
2138    ) {
2139        if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
2140            let argument = argument.map(ToString::to_string);
2141            let output = command.run(
2142                argument.as_deref(),
2143                workspace,
2144                self.lsp_adapter_delegate.clone(),
2145                cx,
2146            );
2147            self.context.update(cx, |context, cx| {
2148                context.insert_command_output(command_range, output, insert_trailing_newline, cx)
2149            });
2150        }
2151    }
2152
2153    fn handle_context_event(
2154        &mut self,
2155        _: Model<Context>,
2156        event: &ContextEvent,
2157        cx: &mut ViewContext<Self>,
2158    ) {
2159        let context_editor = cx.view().downgrade();
2160
2161        match event {
2162            ContextEvent::MessagesEdited => {
2163                self.update_message_headers(cx);
2164                self.context.update(cx, |context, cx| {
2165                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
2166                });
2167            }
2168            ContextEvent::WorkflowStepsRemoved(removed) => {
2169                self.remove_workflow_steps(removed, cx);
2170                cx.notify();
2171            }
2172            ContextEvent::WorkflowStepUpdated(updated) => {
2173                self.update_workflow_step(updated.clone(), cx);
2174                cx.notify();
2175            }
2176            ContextEvent::SummaryChanged => {
2177                cx.emit(EditorEvent::TitleChanged);
2178                self.context.update(cx, |context, cx| {
2179                    context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
2180                });
2181            }
2182            ContextEvent::StreamedCompletion => {
2183                self.editor.update(cx, |editor, cx| {
2184                    if let Some(scroll_position) = self.scroll_position {
2185                        let snapshot = editor.snapshot(cx);
2186                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
2187                        let scroll_top =
2188                            cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
2189                        editor.set_scroll_position(
2190                            point(scroll_position.offset_before_cursor.x, scroll_top),
2191                            cx,
2192                        );
2193                    }
2194                });
2195            }
2196            ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
2197                self.editor.update(cx, |editor, cx| {
2198                    let buffer = editor.buffer().read(cx).snapshot(cx);
2199                    let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
2200                    let excerpt_id = *excerpt_id;
2201
2202                    editor.remove_creases(
2203                        removed
2204                            .iter()
2205                            .filter_map(|range| self.pending_slash_command_creases.remove(range)),
2206                        cx,
2207                    );
2208
2209                    editor.remove_blocks(
2210                        HashSet::from_iter(
2211                            removed.iter().filter_map(|range| {
2212                                self.pending_slash_command_blocks.remove(range)
2213                            }),
2214                        ),
2215                        None,
2216                        cx,
2217                    );
2218
2219                    let crease_ids = editor.insert_creases(
2220                        updated.iter().map(|command| {
2221                            let workspace = self.workspace.clone();
2222                            let confirm_command = Arc::new({
2223                                let context_editor = context_editor.clone();
2224                                let command = command.clone();
2225                                move |cx: &mut WindowContext| {
2226                                    context_editor
2227                                        .update(cx, |context_editor, cx| {
2228                                            context_editor.run_command(
2229                                                command.source_range.clone(),
2230                                                &command.name,
2231                                                command.argument.as_deref(),
2232                                                false,
2233                                                workspace.clone(),
2234                                                cx,
2235                                            );
2236                                        })
2237                                        .ok();
2238                                }
2239                            });
2240                            let placeholder = FoldPlaceholder {
2241                                render: Arc::new(move |_, _, _| Empty.into_any()),
2242                                constrain_width: false,
2243                                merge_adjacent: false,
2244                            };
2245                            let render_toggle = {
2246                                let confirm_command = confirm_command.clone();
2247                                let command = command.clone();
2248                                move |row, _, _, _cx: &mut WindowContext| {
2249                                    render_pending_slash_command_gutter_decoration(
2250                                        row,
2251                                        &command.status,
2252                                        confirm_command.clone(),
2253                                    )
2254                                }
2255                            };
2256                            let render_trailer = {
2257                                let command = command.clone();
2258                                move |row, _unfold, cx: &mut WindowContext| {
2259                                    // TODO: In the future we should investigate how we can expose
2260                                    // this as a hook on the `SlashCommand` trait so that we don't
2261                                    // need to special-case it here.
2262                                    if command.name == DocsSlashCommand::NAME {
2263                                        return render_docs_slash_command_trailer(
2264                                            row,
2265                                            command.clone(),
2266                                            cx,
2267                                        );
2268                                    }
2269
2270                                    Empty.into_any()
2271                                }
2272                            };
2273
2274                            let start = buffer
2275                                .anchor_in_excerpt(excerpt_id, command.source_range.start)
2276                                .unwrap();
2277                            let end = buffer
2278                                .anchor_in_excerpt(excerpt_id, command.source_range.end)
2279                                .unwrap();
2280                            Crease::new(start..end, placeholder, render_toggle, render_trailer)
2281                        }),
2282                        cx,
2283                    );
2284
2285                    let block_ids = editor.insert_blocks(
2286                        updated
2287                            .iter()
2288                            .filter_map(|command| match &command.status {
2289                                PendingSlashCommandStatus::Error(error) => {
2290                                    Some((command, error.clone()))
2291                                }
2292                                _ => None,
2293                            })
2294                            .map(|(command, error_message)| BlockProperties {
2295                                style: BlockStyle::Fixed,
2296                                position: Anchor {
2297                                    buffer_id: Some(buffer_id),
2298                                    excerpt_id,
2299                                    text_anchor: command.source_range.start,
2300                                },
2301                                height: 1,
2302                                disposition: BlockDisposition::Below,
2303                                render: slash_command_error_block_renderer(error_message),
2304                                priority: 0,
2305                            }),
2306                        None,
2307                        cx,
2308                    );
2309
2310                    self.pending_slash_command_creases.extend(
2311                        updated
2312                            .iter()
2313                            .map(|command| command.source_range.clone())
2314                            .zip(crease_ids),
2315                    );
2316
2317                    self.pending_slash_command_blocks.extend(
2318                        updated
2319                            .iter()
2320                            .map(|command| command.source_range.clone())
2321                            .zip(block_ids),
2322                    );
2323                })
2324            }
2325            ContextEvent::SlashCommandFinished {
2326                output_range,
2327                sections,
2328                run_commands_in_output,
2329            } => {
2330                self.insert_slash_command_output_sections(sections.iter().cloned(), cx);
2331
2332                if *run_commands_in_output {
2333                    let commands = self.context.update(cx, |context, cx| {
2334                        context.reparse_slash_commands(cx);
2335                        context
2336                            .pending_commands_for_range(output_range.clone(), cx)
2337                            .to_vec()
2338                    });
2339
2340                    for command in commands {
2341                        self.run_command(
2342                            command.source_range,
2343                            &command.name,
2344                            command.argument.as_deref(),
2345                            false,
2346                            self.workspace.clone(),
2347                            cx,
2348                        );
2349                    }
2350                }
2351            }
2352            ContextEvent::Operation(_) => {}
2353            ContextEvent::AssistError(error_message) => {
2354                self.error_message = Some(SharedString::from(error_message.clone()));
2355            }
2356        }
2357    }
2358
2359    fn insert_slash_command_output_sections(
2360        &mut self,
2361        sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
2362        cx: &mut ViewContext<Self>,
2363    ) {
2364        self.editor.update(cx, |editor, cx| {
2365            let buffer = editor.buffer().read(cx).snapshot(cx);
2366            let excerpt_id = *buffer.as_singleton().unwrap().0;
2367            let mut buffer_rows_to_fold = BTreeSet::new();
2368            let mut creases = Vec::new();
2369            for section in sections {
2370                let start = buffer
2371                    .anchor_in_excerpt(excerpt_id, section.range.start)
2372                    .unwrap();
2373                let end = buffer
2374                    .anchor_in_excerpt(excerpt_id, section.range.end)
2375                    .unwrap();
2376                let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2377                buffer_rows_to_fold.insert(buffer_row);
2378                creases.push(Crease::new(
2379                    start..end,
2380                    FoldPlaceholder {
2381                        render: Arc::new({
2382                            let editor = cx.view().downgrade();
2383                            let icon = section.icon;
2384                            let label = section.label.clone();
2385                            move |fold_id, fold_range, _cx| {
2386                                let editor = editor.clone();
2387                                ButtonLike::new(fold_id)
2388                                    .style(ButtonStyle::Filled)
2389                                    .layer(ElevationIndex::ElevatedSurface)
2390                                    .child(Icon::new(icon))
2391                                    .child(Label::new(label.clone()).single_line())
2392                                    .on_click(move |_, cx| {
2393                                        editor
2394                                            .update(cx, |editor, cx| {
2395                                                let buffer_start = fold_range
2396                                                    .start
2397                                                    .to_point(&editor.buffer().read(cx).read(cx));
2398                                                let buffer_row = MultiBufferRow(buffer_start.row);
2399                                                editor.unfold_at(&UnfoldAt { buffer_row }, cx);
2400                                            })
2401                                            .ok();
2402                                    })
2403                                    .into_any_element()
2404                            }
2405                        }),
2406                        constrain_width: false,
2407                        merge_adjacent: false,
2408                    },
2409                    render_slash_command_output_toggle,
2410                    |_, _, _| Empty.into_any_element(),
2411                ));
2412            }
2413
2414            editor.insert_creases(creases, cx);
2415
2416            for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2417                editor.fold_at(&FoldAt { buffer_row }, cx);
2418            }
2419        });
2420    }
2421
2422    fn handle_editor_event(
2423        &mut self,
2424        _: View<Editor>,
2425        event: &EditorEvent,
2426        cx: &mut ViewContext<Self>,
2427    ) {
2428        match event {
2429            EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2430                let cursor_scroll_position = self.cursor_scroll_position(cx);
2431                if *autoscroll {
2432                    self.scroll_position = cursor_scroll_position;
2433                } else if self.scroll_position != cursor_scroll_position {
2434                    self.scroll_position = None;
2435                }
2436            }
2437            EditorEvent::SelectionsChanged { .. } => {
2438                self.scroll_position = self.cursor_scroll_position(cx);
2439                self.update_active_workflow_step(cx);
2440            }
2441            _ => {}
2442        }
2443        cx.emit(event.clone());
2444    }
2445
2446    fn active_workflow_step(&self) -> Option<&WorkflowStep> {
2447        let step = self.active_workflow_step.as_ref()?;
2448        self.workflow_steps.get(&step.range)
2449    }
2450
2451    fn remove_workflow_steps(
2452        &mut self,
2453        removed_steps: &[Range<language::Anchor>],
2454        cx: &mut ViewContext<Self>,
2455    ) {
2456        let mut blocks_to_remove = HashSet::default();
2457        for step_range in removed_steps {
2458            self.hide_workflow_step(step_range.clone(), cx);
2459            if let Some(step) = self.workflow_steps.remove(step_range) {
2460                blocks_to_remove.insert(step.header_block_id);
2461                blocks_to_remove.insert(step.footer_block_id);
2462            }
2463            if let Some(debug) = self.debug_inspector.as_mut() {
2464                debug.deactivate_for(step_range, cx);
2465            }
2466        }
2467        self.editor.update(cx, |editor, cx| {
2468            editor.remove_blocks(blocks_to_remove, None, cx)
2469        });
2470        self.update_active_workflow_step(cx);
2471    }
2472
2473    fn update_workflow_step(
2474        &mut self,
2475        step_range: Range<language::Anchor>,
2476        cx: &mut ViewContext<Self>,
2477    ) {
2478        let buffer_snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2479        let (&excerpt_id, _, _) = buffer_snapshot.as_singleton().unwrap();
2480
2481        let Some(step) = self
2482            .context
2483            .read(cx)
2484            .workflow_step_for_range(step_range.clone())
2485        else {
2486            return;
2487        };
2488
2489        let resolved_step = step.status.into_resolved();
2490        if let Some(existing_step) = self.workflow_steps.get_mut(&step_range) {
2491            existing_step.resolved_step = resolved_step;
2492            if let Some(debug) = self.debug_inspector.as_mut() {
2493                debug.refresh(&step_range, cx);
2494            }
2495        } else {
2496            let start = buffer_snapshot
2497                .anchor_in_excerpt(excerpt_id, step_range.start)
2498                .unwrap();
2499            let end = buffer_snapshot
2500                .anchor_in_excerpt(excerpt_id, step_range.end)
2501                .unwrap();
2502            let weak_self = cx.view().downgrade();
2503            let block_ids = self.editor.update(cx, |editor, cx| {
2504                let step_range = step_range.clone();
2505                let editor_focus_handle = editor.focus_handle(cx);
2506                editor.insert_blocks(
2507                    vec![
2508                        BlockProperties {
2509                            position: start,
2510                            height: 1,
2511                            style: BlockStyle::Sticky,
2512                            render: Box::new({
2513                                let weak_self = weak_self.clone();
2514                                let step_range = step_range.clone();
2515                                move |cx| {
2516                                    let current_status = weak_self
2517                                        .update(&mut **cx, |context_editor, cx| {
2518                                            let step =
2519                                                context_editor.workflow_steps.get(&step_range)?;
2520                                            Some(step.status(cx))
2521                                        })
2522                                        .ok()
2523                                        .flatten();
2524
2525                                    let theme = cx.theme().status();
2526                                    let border_color = if current_status
2527                                        .as_ref()
2528                                        .map_or(false, |status| status.is_confirmed())
2529                                    {
2530                                        theme.ignored_border
2531                                    } else {
2532                                        theme.info_border
2533                                    };
2534                                    let step_index = weak_self.update(&mut **cx, |this, cx| {
2535                                       let snapshot = this.editor.read(cx).buffer().read(cx).as_singleton()?.read(cx).text_snapshot();
2536                                       let start_offset = step_range.start.to_offset(&snapshot);
2537                                       let parent_message = this.context.read(cx).messages_for_offsets([start_offset], cx);
2538                                       debug_assert_eq!(parent_message.len(), 1);
2539                                       let parent_message = parent_message.first()?;
2540
2541                                       let index_of_current_step = this.workflow_steps.keys().filter(|workflow_step_range| workflow_step_range.start.cmp(&parent_message.anchor, &snapshot).is_ge() && workflow_step_range.end.cmp(&step_range.end, &snapshot).is_le()).count();
2542                                       Some(index_of_current_step)
2543                                    }).ok().flatten();
2544
2545                                    let debug_header = weak_self
2546                                        .update(&mut **cx, |this, _| {
2547                                            if let Some(inspector) = this.debug_inspector.as_mut() {
2548                                                Some(inspector.is_active(&step_range))
2549                                            } else {
2550                                                None
2551                                            }
2552                                        })
2553                                        .unwrap_or_default();
2554                                    let step_label = if let Some(index) = step_index {
2555
2556                                        Label::new(format!("Step {index}")).size(LabelSize::Small)
2557                                        } else {
2558                                            Label::new("Step").size(LabelSize::Small)
2559                                        };
2560                                    let step_label = if current_status.as_ref().is_some_and(|status| status.is_confirmed()) {
2561                                        h_flex().items_center().gap_2().child(step_label.strikethrough(true).color(Color::Muted)).child(Icon::new(IconName::Check).size(IconSize::Small).color(Color::Created))
2562                                    } else {
2563                                        div().child(step_label)
2564                                    };
2565                                    div()
2566                                        .w_full()
2567                                        .px(cx.gutter_dimensions.full_width())
2568                                        .child(
2569                                            h_flex()
2570                                                .w_full()
2571                                                .border_b_1()
2572                                                .border_color(border_color)
2573                                                .pb_1p5()
2574                                                .justify_between()
2575                                                .gap_2()
2576                                                .child(h_flex().justify_start().gap_2().child(step_label).children(
2577                                                    debug_header.map(|is_active| {
2578
2579                                                        Button::new("debug-workflows-toggle", "Debug")
2580                                                            .icon_color(Color::Hidden)
2581                                                            .color(Color::Hidden)
2582                                                            .selected_icon_color(Color::Default)
2583                                                            .selected_label_color(Color::Default)
2584                                                            .icon(IconName::Microscope)
2585                                                            .icon_position(IconPosition::Start)
2586                                                            .icon_size(IconSize::Small)
2587                                                            .label_size(LabelSize::Small)
2588                                                            .selected(is_active)
2589                                                            .on_click({
2590                                                                let weak_self = weak_self.clone();
2591                                                                let step_range = step_range.clone();
2592                                                                move |_, cx| {
2593                                                                    weak_self
2594                                                                        .update(cx, |this, cx| {
2595                                                                            if let Some(inspector) =
2596                                                                                this.debug_inspector
2597                                                                                    .as_mut()
2598                                                                            {
2599                                                                                if is_active {
2600
2601                                                                                    inspector.deactivate_for(&step_range, cx);
2602                                                                                } else {
2603                                                                                    inspector.activate_for_step(step_range.clone(), cx);
2604                                                                                }
2605                                                                            }
2606                                                                        })
2607                                                                        .ok();
2608                                                                }
2609                                                            })
2610                                                    })
2611
2612                                                ))
2613                                                .children(current_status.as_ref().map(|status| {
2614                                                    h_flex().w_full().justify_end().child(
2615                                                        status.into_element(
2616                                                            step_range.clone(),
2617                                                            editor_focus_handle.clone(),
2618                                                            weak_self.clone(),
2619                                                            cx,
2620                                                        ),
2621                                                    )
2622                                                })),
2623                                        )
2624                                        .into_any()
2625                                }
2626                            }),
2627                            disposition: BlockDisposition::Above,
2628                            priority: 0,
2629                        },
2630                        BlockProperties {
2631                            position: end,
2632                            height: 0,
2633                            style: BlockStyle::Sticky,
2634                            render: Box::new(move |cx| {
2635                                let current_status = weak_self
2636                                    .update(&mut **cx, |context_editor, cx| {
2637                                        let step =
2638                                            context_editor.workflow_steps.get(&step_range)?;
2639                                        Some(step.status(cx))
2640                                    })
2641                                    .ok()
2642                                    .flatten();
2643                                let theme = cx.theme().status();
2644                                let border_color = if current_status
2645                                    .as_ref()
2646                                    .map_or(false, |status| status.is_confirmed())
2647                                {
2648                                    theme.ignored_border
2649                                } else {
2650                                    theme.info_border
2651                                };
2652
2653                                div()
2654                                    .w_full()
2655                                    .px(cx.gutter_dimensions.full_width())
2656                                    .child(h_flex().h(px(1.)).bg(border_color))
2657                                    .into_any()
2658                            }),
2659                            disposition: BlockDisposition::Below,
2660                            priority: 0,
2661                        },
2662                    ],
2663                    None,
2664                    cx,
2665                )
2666            });
2667            self.workflow_steps.insert(
2668                step_range.clone(),
2669                WorkflowStep {
2670                    range: step_range.clone(),
2671                    header_block_id: block_ids[0],
2672                    footer_block_id: block_ids[1],
2673                    resolved_step,
2674                    assist: None,
2675                },
2676            );
2677        }
2678
2679        self.update_active_workflow_step(cx);
2680    }
2681
2682    fn update_active_workflow_step(&mut self, cx: &mut ViewContext<Self>) {
2683        let new_step = self.active_workflow_step_for_cursor(cx);
2684        if new_step.as_ref() != self.active_workflow_step.as_ref() {
2685            if let Some(old_step) = self.active_workflow_step.take() {
2686                self.hide_workflow_step(old_step.range, cx);
2687            }
2688
2689            if let Some(new_step) = new_step {
2690                self.show_workflow_step(new_step.range.clone(), cx);
2691                self.active_workflow_step = Some(new_step);
2692            }
2693        }
2694    }
2695
2696    fn hide_workflow_step(
2697        &mut self,
2698        step_range: Range<language::Anchor>,
2699        cx: &mut ViewContext<Self>,
2700    ) {
2701        let Some(step) = self.workflow_steps.get_mut(&step_range) else {
2702            return;
2703        };
2704        let Some(assist) = step.assist.as_ref() else {
2705            return;
2706        };
2707        let Some(editor) = assist.editor.upgrade() else {
2708            return;
2709        };
2710
2711        if matches!(step.status(cx), WorkflowStepStatus::Idle) {
2712            let assist = step.assist.take().unwrap();
2713            InlineAssistant::update_global(cx, |assistant, cx| {
2714                for assist_id in assist.assist_ids {
2715                    assistant.finish_assist(assist_id, true, cx)
2716                }
2717            });
2718
2719            self.workspace
2720                .update(cx, |workspace, cx| {
2721                    if let Some(pane) = workspace.pane_for(&editor) {
2722                        pane.update(cx, |pane, cx| {
2723                            let item_id = editor.entity_id();
2724                            if !assist.editor_was_open && pane.is_active_preview_item(item_id) {
2725                                pane.close_item_by_id(item_id, SaveIntent::Skip, cx)
2726                                    .detach_and_log_err(cx);
2727                            }
2728                        });
2729                    }
2730                })
2731                .ok();
2732        }
2733    }
2734
2735    fn show_workflow_step(
2736        &mut self,
2737        step_range: Range<language::Anchor>,
2738        cx: &mut ViewContext<Self>,
2739    ) {
2740        let Some(step) = self.workflow_steps.get_mut(&step_range) else {
2741            return;
2742        };
2743
2744        let mut scroll_to_assist_id = None;
2745        match step.status(cx) {
2746            WorkflowStepStatus::Idle => {
2747                if let Some(assist) = step.assist.as_ref() {
2748                    scroll_to_assist_id = assist.assist_ids.first().copied();
2749                } else if let Some(Ok(resolved)) = step.resolved_step.as_ref() {
2750                    step.assist = Self::open_assists_for_step(
2751                        resolved,
2752                        &self.project,
2753                        &self.assistant_panel,
2754                        &self.workspace,
2755                        cx,
2756                    );
2757                }
2758            }
2759            WorkflowStepStatus::Pending => {
2760                if let Some(assist) = step.assist.as_ref() {
2761                    let assistant = InlineAssistant::global(cx);
2762                    scroll_to_assist_id = assist
2763                        .assist_ids
2764                        .iter()
2765                        .copied()
2766                        .find(|assist_id| assistant.assist_status(*assist_id, cx).is_pending());
2767                }
2768            }
2769            WorkflowStepStatus::Done => {
2770                if let Some(assist) = step.assist.as_ref() {
2771                    scroll_to_assist_id = assist.assist_ids.first().copied();
2772                }
2773            }
2774            _ => {}
2775        }
2776
2777        if let Some(assist_id) = scroll_to_assist_id {
2778            if let Some(editor) = step
2779                .assist
2780                .as_ref()
2781                .and_then(|assists| assists.editor.upgrade())
2782            {
2783                self.workspace
2784                    .update(cx, |workspace, cx| {
2785                        workspace.activate_item(&editor, false, false, cx);
2786                    })
2787                    .ok();
2788                InlineAssistant::update_global(cx, |assistant, cx| {
2789                    assistant.scroll_to_assist(assist_id, cx)
2790                });
2791            }
2792        }
2793    }
2794
2795    fn open_assists_for_step(
2796        resolved_step: &ResolvedWorkflowStep,
2797        project: &Model<Project>,
2798        assistant_panel: &WeakView<AssistantPanel>,
2799        workspace: &WeakView<Workspace>,
2800        cx: &mut ViewContext<Self>,
2801    ) -> Option<WorkflowAssist> {
2802        let assistant_panel = assistant_panel.upgrade()?;
2803        if resolved_step.suggestions.is_empty() {
2804            return None;
2805        }
2806
2807        let editor;
2808        let mut editor_was_open = false;
2809        let mut suggestion_groups = Vec::new();
2810        if resolved_step.suggestions.len() == 1
2811            && resolved_step.suggestions.values().next().unwrap().len() == 1
2812        {
2813            // If there's only one buffer and one suggestion group, open it directly
2814            let (buffer, groups) = resolved_step.suggestions.iter().next().unwrap();
2815            let group = groups.into_iter().next().unwrap();
2816            editor = workspace
2817                .update(cx, |workspace, cx| {
2818                    let active_pane = workspace.active_pane().clone();
2819                    editor_was_open =
2820                        workspace.is_project_item_open::<Editor>(&active_pane, buffer, cx);
2821                    workspace.open_project_item::<Editor>(
2822                        active_pane,
2823                        buffer.clone(),
2824                        false,
2825                        false,
2826                        cx,
2827                    )
2828                })
2829                .log_err()?;
2830
2831            let (&excerpt_id, _, _) = editor
2832                .read(cx)
2833                .buffer()
2834                .read(cx)
2835                .read(cx)
2836                .as_singleton()
2837                .unwrap();
2838
2839            // Scroll the editor to the suggested assist
2840            editor.update(cx, |editor, cx| {
2841                let multibuffer = editor.buffer().read(cx).snapshot(cx);
2842                let (&excerpt_id, _, buffer) = multibuffer.as_singleton().unwrap();
2843                let anchor = if group.context_range.start.to_offset(buffer) == 0 {
2844                    Anchor::min()
2845                } else {
2846                    multibuffer
2847                        .anchor_in_excerpt(excerpt_id, group.context_range.start)
2848                        .unwrap()
2849                };
2850
2851                editor.set_scroll_anchor(
2852                    ScrollAnchor {
2853                        offset: gpui::Point::default(),
2854                        anchor,
2855                    },
2856                    cx,
2857                );
2858            });
2859
2860            suggestion_groups.push((excerpt_id, group));
2861        } else {
2862            // If there are multiple buffers or suggestion groups, create a multibuffer
2863            let multibuffer = cx.new_model(|cx| {
2864                let replica_id = project.read(cx).replica_id();
2865                let mut multibuffer = MultiBuffer::new(replica_id, Capability::ReadWrite)
2866                    .with_title(resolved_step.title.clone());
2867                for (buffer, groups) in &resolved_step.suggestions {
2868                    let excerpt_ids = multibuffer.push_excerpts(
2869                        buffer.clone(),
2870                        groups.iter().map(|suggestion_group| ExcerptRange {
2871                            context: suggestion_group.context_range.clone(),
2872                            primary: None,
2873                        }),
2874                        cx,
2875                    );
2876                    suggestion_groups.extend(excerpt_ids.into_iter().zip(groups));
2877                }
2878                multibuffer
2879            });
2880
2881            editor = cx.new_view(|cx| {
2882                Editor::for_multibuffer(multibuffer, Some(project.clone()), true, cx)
2883            });
2884            workspace
2885                .update(cx, |workspace, cx| {
2886                    workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
2887                })
2888                .log_err()?;
2889        }
2890
2891        let mut assist_ids = Vec::new();
2892        for (excerpt_id, suggestion_group) in suggestion_groups {
2893            for suggestion in &suggestion_group.suggestions {
2894                assist_ids.extend(suggestion.show(
2895                    &editor,
2896                    excerpt_id,
2897                    workspace,
2898                    &assistant_panel,
2899                    cx,
2900                ));
2901            }
2902        }
2903
2904        let mut observations = Vec::new();
2905        InlineAssistant::update_global(cx, |assistant, _cx| {
2906            for assist_id in &assist_ids {
2907                observations.push(assistant.observe_assist(*assist_id));
2908            }
2909        });
2910
2911        Some(WorkflowAssist {
2912            assist_ids,
2913            editor: editor.downgrade(),
2914            editor_was_open,
2915            _observe_assist_status: cx.spawn(|this, mut cx| async move {
2916                while !observations.is_empty() {
2917                    let (result, ix, _) = futures::future::select_all(
2918                        observations
2919                            .iter_mut()
2920                            .map(|observation| Box::pin(observation.changed())),
2921                    )
2922                    .await;
2923
2924                    if result.is_err() {
2925                        observations.remove(ix);
2926                    }
2927
2928                    if this.update(&mut cx, |_, cx| cx.notify()).is_err() {
2929                        break;
2930                    }
2931                }
2932            }),
2933        })
2934    }
2935
2936    fn handle_editor_search_event(
2937        &mut self,
2938        _: View<Editor>,
2939        event: &SearchEvent,
2940        cx: &mut ViewContext<Self>,
2941    ) {
2942        cx.emit(event.clone());
2943    }
2944
2945    fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2946        self.editor.update(cx, |editor, cx| {
2947            let snapshot = editor.snapshot(cx);
2948            let cursor = editor.selections.newest_anchor().head();
2949            let cursor_row = cursor
2950                .to_display_point(&snapshot.display_snapshot)
2951                .row()
2952                .as_f32();
2953            let scroll_position = editor
2954                .scroll_manager
2955                .anchor()
2956                .scroll_position(&snapshot.display_snapshot);
2957
2958            let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2959            if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2960                Some(ScrollPosition {
2961                    cursor,
2962                    offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2963                })
2964            } else {
2965                None
2966            }
2967        })
2968    }
2969
2970    fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2971        self.editor.update(cx, |editor, cx| {
2972            let buffer = editor.buffer().read(cx).snapshot(cx);
2973            let excerpt_id = *buffer.as_singleton().unwrap().0;
2974            let old_blocks = std::mem::take(&mut self.blocks);
2975            let new_blocks = self
2976                .context
2977                .read(cx)
2978                .messages(cx)
2979                .map(|message| BlockProperties {
2980                    position: buffer
2981                        .anchor_in_excerpt(excerpt_id, message.anchor)
2982                        .unwrap(),
2983                    height: 2,
2984                    style: BlockStyle::Sticky,
2985                    render: Box::new({
2986                        let context = self.context.clone();
2987                        move |cx| {
2988                            let message_id = message.id;
2989                            let show_spinner = message.role == Role::Assistant
2990                                && message.status == MessageStatus::Pending;
2991
2992                            let label = match message.role {
2993                                Role::User => {
2994                                    Label::new("You").color(Color::Default).into_any_element()
2995                                }
2996                                Role::Assistant => {
2997                                    let label = Label::new("Assistant").color(Color::Info);
2998                                    if show_spinner {
2999                                        label
3000                                            .with_animation(
3001                                                "pulsating-label",
3002                                                Animation::new(Duration::from_secs(2))
3003                                                    .repeat()
3004                                                    .with_easing(pulsating_between(0.2, 1.0)),
3005                                                |label, delta| label.alpha(delta),
3006                                            )
3007                                            .into_any_element()
3008                                    } else {
3009                                        label.into_any_element()
3010                                    }
3011                                }
3012
3013                                Role::System => Label::new("System")
3014                                    .color(Color::Warning)
3015                                    .into_any_element(),
3016                            };
3017
3018                            let sender = ButtonLike::new("role")
3019                                .style(ButtonStyle::Filled)
3020                                .child(label)
3021                                .tooltip(|cx| {
3022                                    Tooltip::with_meta(
3023                                        "Toggle message role",
3024                                        None,
3025                                        "Available roles: You (User), Assistant, System",
3026                                        cx,
3027                                    )
3028                                })
3029                                .on_click({
3030                                    let context = context.clone();
3031                                    move |_, cx| {
3032                                        context.update(cx, |context, cx| {
3033                                            context.cycle_message_roles(
3034                                                HashSet::from_iter(Some(message_id)),
3035                                                cx,
3036                                            )
3037                                        })
3038                                    }
3039                                });
3040
3041                            let trigger = Button::new("show-error", "Error")
3042                                .color(Color::Error)
3043                                .selected_label_color(Color::Error)
3044                                .selected_icon_color(Color::Error)
3045                                .icon(IconName::XCircle)
3046                                .icon_color(Color::Error)
3047                                .icon_size(IconSize::Small)
3048                                .icon_position(IconPosition::Start)
3049                                .tooltip(move |cx| {
3050                                    Tooltip::with_meta(
3051                                        "Error interacting with language model",
3052                                        None,
3053                                        "Click for more details",
3054                                        cx,
3055                                    )
3056                                });
3057                            h_flex()
3058                                .id(("message_header", message_id.as_u64()))
3059                                .pl(cx.gutter_dimensions.full_width())
3060                                .h_11()
3061                                .w_full()
3062                                .relative()
3063                                .gap_1()
3064                                .child(sender)
3065                                .children(
3066                                    if let MessageStatus::Error(error) = message.status.clone() {
3067                                        Some(
3068                                            PopoverMenu::new("show-error-popover")
3069                                                .menu(move |cx| {
3070                                                    Some(cx.new_view(|cx| ErrorPopover {
3071                                                        error: error.clone(),
3072                                                        focus_handle: cx.focus_handle(),
3073                                                    }))
3074                                                })
3075                                                .trigger(trigger),
3076                                        )
3077                                    } else {
3078                                        None
3079                                    },
3080                                )
3081                                .into_any_element()
3082                        }
3083                    }),
3084                    disposition: BlockDisposition::Above,
3085                    priority: usize::MAX,
3086                })
3087                .collect::<Vec<_>>();
3088
3089            editor.remove_blocks(old_blocks, None, cx);
3090            let ids = editor.insert_blocks(new_blocks, None, cx);
3091            self.blocks = HashSet::from_iter(ids);
3092        });
3093    }
3094
3095    fn insert_selection(
3096        workspace: &mut Workspace,
3097        _: &InsertIntoEditor,
3098        cx: &mut ViewContext<Workspace>,
3099    ) {
3100        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
3101            return;
3102        };
3103        let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
3104            return;
3105        };
3106        let Some(active_editor_view) = workspace
3107            .active_item(cx)
3108            .and_then(|item| item.act_as::<Editor>(cx))
3109        else {
3110            return;
3111        };
3112
3113        let context_editor = context_editor_view.read(cx).editor.read(cx);
3114        let anchor = context_editor.selections.newest_anchor();
3115        let text = context_editor
3116            .buffer()
3117            .read(cx)
3118            .read(cx)
3119            .text_for_range(anchor.range())
3120            .collect::<String>();
3121
3122        // If nothing is selected, don't delete the current selection; instead, be a no-op.
3123        if !text.is_empty() {
3124            active_editor_view.update(cx, |editor, cx| {
3125                editor.insert(&text, cx);
3126                editor.focus(cx);
3127            })
3128        }
3129    }
3130
3131    fn quote_selection(
3132        workspace: &mut Workspace,
3133        _: &QuoteSelection,
3134        cx: &mut ViewContext<Workspace>,
3135    ) {
3136        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
3137            return;
3138        };
3139        let Some(editor) = workspace
3140            .active_item(cx)
3141            .and_then(|item| item.act_as::<Editor>(cx))
3142        else {
3143            return;
3144        };
3145
3146        let selection = editor.update(cx, |editor, cx| editor.selections.newest_adjusted(cx));
3147        let editor = editor.read(cx);
3148        let buffer = editor.buffer().read(cx).snapshot(cx);
3149        let range = editor::ToOffset::to_offset(&selection.start, &buffer)
3150            ..editor::ToOffset::to_offset(&selection.end, &buffer);
3151        let selected_text = buffer.text_for_range(range.clone()).collect::<String>();
3152        if selected_text.is_empty() {
3153            return;
3154        }
3155
3156        let start_language = buffer.language_at(range.start);
3157        let end_language = buffer.language_at(range.end);
3158        let language_name = if start_language == end_language {
3159            start_language.map(|language| language.code_fence_block_name())
3160        } else {
3161            None
3162        };
3163        let language_name = language_name.as_deref().unwrap_or("");
3164
3165        let filename = buffer
3166            .file_at(selection.start)
3167            .map(|file| file.full_path(cx));
3168
3169        let text = if language_name == "markdown" {
3170            selected_text
3171                .lines()
3172                .map(|line| format!("> {}", line))
3173                .collect::<Vec<_>>()
3174                .join("\n")
3175        } else {
3176            let start_symbols = buffer
3177                .symbols_containing(selection.start, None)
3178                .map(|(_, symbols)| symbols);
3179            let end_symbols = buffer
3180                .symbols_containing(selection.end, None)
3181                .map(|(_, symbols)| symbols);
3182
3183            let outline_text =
3184                if let Some((start_symbols, end_symbols)) = start_symbols.zip(end_symbols) {
3185                    Some(
3186                        start_symbols
3187                            .into_iter()
3188                            .zip(end_symbols)
3189                            .take_while(|(a, b)| a == b)
3190                            .map(|(a, _)| a.text)
3191                            .collect::<Vec<_>>()
3192                            .join(" > "),
3193                    )
3194                } else {
3195                    None
3196                };
3197
3198            let line_comment_prefix = start_language
3199                .and_then(|l| l.default_scope().line_comment_prefixes().first().cloned());
3200
3201            let fence = codeblock_fence_for_path(
3202                filename.as_deref(),
3203                Some(selection.start.row..selection.end.row),
3204            );
3205
3206            if let Some((line_comment_prefix, outline_text)) = line_comment_prefix.zip(outline_text)
3207            {
3208                let breadcrumb = format!("{line_comment_prefix}Excerpt from: {outline_text}\n");
3209                format!("{fence}{breadcrumb}{selected_text}\n```")
3210            } else {
3211                format!("{fence}{selected_text}\n```")
3212            }
3213        };
3214
3215        let crease_title = if let Some(path) = filename {
3216            let start_line = selection.start.row + 1;
3217            let end_line = selection.end.row + 1;
3218            if start_line == end_line {
3219                format!("{}, Line {}", path.display(), start_line)
3220            } else {
3221                format!("{}, Lines {} to {}", path.display(), start_line, end_line)
3222            }
3223        } else {
3224            "Quoted selection".to_string()
3225        };
3226
3227        // Activate the panel
3228        if !panel.focus_handle(cx).contains_focused(cx) {
3229            workspace.toggle_panel_focus::<AssistantPanel>(cx);
3230        }
3231
3232        panel.update(cx, |_, cx| {
3233            // Wait to create a new context until the workspace is no longer
3234            // being updated.
3235            cx.defer(move |panel, cx| {
3236                if let Some(context) = panel
3237                    .active_context_editor(cx)
3238                    .or_else(|| panel.new_context(cx))
3239                {
3240                    context.update(cx, |context, cx| {
3241                        context.editor.update(cx, |editor, cx| {
3242                            editor.insert("\n", cx);
3243
3244                            let point = editor.selections.newest::<Point>(cx).head();
3245                            let start_row = MultiBufferRow(point.row);
3246
3247                            editor.insert(&text, cx);
3248
3249                            let snapshot = editor.buffer().read(cx).snapshot(cx);
3250                            let anchor_before = snapshot.anchor_after(point);
3251                            let anchor_after = editor
3252                                .selections
3253                                .newest_anchor()
3254                                .head()
3255                                .bias_left(&snapshot);
3256
3257                            editor.insert("\n", cx);
3258
3259                            let fold_placeholder = quote_selection_fold_placeholder(
3260                                crease_title,
3261                                cx.view().downgrade(),
3262                            );
3263                            let crease = Crease::new(
3264                                anchor_before..anchor_after,
3265                                fold_placeholder,
3266                                render_quote_selection_output_toggle,
3267                                |_, _, _| Empty.into_any(),
3268                            );
3269                            editor.insert_creases(vec![crease], cx);
3270                            editor.fold_at(
3271                                &FoldAt {
3272                                    buffer_row: start_row,
3273                                },
3274                                cx,
3275                            );
3276                        })
3277                    });
3278                };
3279            });
3280        });
3281    }
3282
3283    fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
3284        let editor = self.editor.read(cx);
3285        let context = self.context.read(cx);
3286        if editor.selections.count() == 1 {
3287            let selection = editor.selections.newest::<usize>(cx);
3288            let mut copied_text = String::new();
3289            let mut spanned_messages = 0;
3290            for message in context.messages(cx) {
3291                if message.offset_range.start >= selection.range().end {
3292                    break;
3293                } else if message.offset_range.end >= selection.range().start {
3294                    let range = cmp::max(message.offset_range.start, selection.range().start)
3295                        ..cmp::min(message.offset_range.end, selection.range().end);
3296                    if !range.is_empty() {
3297                        spanned_messages += 1;
3298                        write!(&mut copied_text, "## {}\n\n", message.role).unwrap();
3299                        for chunk in context.buffer().read(cx).text_for_range(range) {
3300                            copied_text.push_str(chunk);
3301                        }
3302                        copied_text.push('\n');
3303                    }
3304                }
3305            }
3306
3307            if spanned_messages > 1 {
3308                cx.write_to_clipboard(ClipboardItem::new(copied_text));
3309                return;
3310            }
3311        }
3312
3313        cx.propagate();
3314    }
3315
3316    fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
3317        self.context.update(cx, |context, cx| {
3318            let selections = self.editor.read(cx).selections.disjoint_anchors();
3319            for selection in selections.as_ref() {
3320                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
3321                let range = selection
3322                    .map(|endpoint| endpoint.to_offset(&buffer))
3323                    .range();
3324                context.split_message(range, cx);
3325            }
3326        });
3327    }
3328
3329    fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
3330        self.context.update(cx, |context, cx| {
3331            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
3332        });
3333    }
3334
3335    fn title(&self, cx: &AppContext) -> Cow<str> {
3336        self.context
3337            .read(cx)
3338            .summary()
3339            .map(|summary| summary.text.clone())
3340            .map(Cow::Owned)
3341            .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
3342    }
3343
3344    fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3345        use feature_flags::FeatureFlagAppExt;
3346        let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
3347            assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
3348        });
3349
3350        if nudge.map_or(false, |value| value) {
3351            Some(
3352                h_flex()
3353                    .p_3()
3354                    .border_b_1()
3355                    .border_color(cx.theme().colors().border_variant)
3356                    .bg(cx.theme().colors().editor_background)
3357                    .justify_between()
3358                    .child(
3359                        h_flex()
3360                            .gap_3()
3361                            .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
3362                            .child(Label::new("Zed AI is here! Get started by signing in →")),
3363                    )
3364                    .child(
3365                        Button::new("sign-in", "Sign in")
3366                            .size(ButtonSize::Compact)
3367                            .style(ButtonStyle::Filled)
3368                            .on_click(cx.listener(|this, _event, cx| {
3369                                let client = this
3370                                    .workspace
3371                                    .update(cx, |workspace, _| workspace.client().clone())
3372                                    .log_err();
3373
3374                                if let Some(client) = client {
3375                                    cx.spawn(|this, mut cx| async move {
3376                                        client.authenticate_and_connect(true, &mut cx).await?;
3377                                        this.update(&mut cx, |_, cx| cx.notify())
3378                                    })
3379                                    .detach_and_log_err(cx)
3380                                }
3381                            })),
3382                    )
3383                    .into_any_element(),
3384            )
3385        } else if let Some(configuration_error) = configuration_error(cx) {
3386            let label = match configuration_error {
3387                ConfigurationError::NoProvider => "No LLM provider selected.",
3388                ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
3389            };
3390            Some(
3391                h_flex()
3392                    .p_3()
3393                    .border_b_1()
3394                    .border_color(cx.theme().colors().border_variant)
3395                    .bg(cx.theme().colors().editor_background)
3396                    .justify_between()
3397                    .child(
3398                        h_flex()
3399                            .gap_3()
3400                            .child(
3401                                Icon::new(IconName::ExclamationTriangle)
3402                                    .size(IconSize::Small)
3403                                    .color(Color::Warning),
3404                            )
3405                            .child(Label::new(label)),
3406                    )
3407                    .child(
3408                        Button::new("open-configuration", "Open configuration")
3409                            .size(ButtonSize::Compact)
3410                            .icon_size(IconSize::Small)
3411                            .style(ButtonStyle::Filled)
3412                            .on_click({
3413                                let focus_handle = self.focus_handle(cx).clone();
3414                                move |_event, cx| {
3415                                    focus_handle.dispatch_action(&ShowConfiguration, cx);
3416                                }
3417                            }),
3418                    )
3419                    .into_any_element(),
3420            )
3421        } else {
3422            None
3423        }
3424    }
3425
3426    fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3427        let focus_handle = self.focus_handle(cx).clone();
3428        let button_text = match self.active_workflow_step() {
3429            Some(step) => match step.status(cx) {
3430                WorkflowStepStatus::Resolving => "Resolving Step...",
3431                WorkflowStepStatus::Error(_) => "Retry Step Resolution",
3432                WorkflowStepStatus::Idle => "Transform",
3433                WorkflowStepStatus::Pending => "Transforming...",
3434                WorkflowStepStatus::Done => "Accept Transformation",
3435                WorkflowStepStatus::Confirmed => "Send",
3436            },
3437            None => "Send",
3438        };
3439
3440        let (style, tooltip) = match token_state(&self.context, cx) {
3441            Some(TokenState::NoTokensLeft { .. }) => (
3442                ButtonStyle::Tinted(TintColor::Negative),
3443                Some(Tooltip::text("Token limit reached", cx)),
3444            ),
3445            Some(TokenState::HasMoreTokens {
3446                over_warn_threshold,
3447                ..
3448            }) => {
3449                let (style, tooltip) = if over_warn_threshold {
3450                    (
3451                        ButtonStyle::Tinted(TintColor::Warning),
3452                        Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3453                    )
3454                } else {
3455                    (ButtonStyle::Filled, None)
3456                };
3457                (style, tooltip)
3458            }
3459            None => (ButtonStyle::Filled, None),
3460        };
3461
3462        let provider = LanguageModelRegistry::read_global(cx).active_provider();
3463        let disabled = self.show_accept_terms
3464            && provider
3465                .as_ref()
3466                .map_or(false, |provider| provider.must_accept_terms(cx));
3467
3468        ButtonLike::new("send_button")
3469            .disabled(disabled)
3470            .style(style)
3471            .when_some(tooltip, |button, tooltip| {
3472                button.tooltip(move |_| tooltip.clone())
3473            })
3474            .layer(ElevationIndex::ModalSurface)
3475            .children(
3476                KeyBinding::for_action_in(&Assist, &focus_handle, cx)
3477                    .map(|binding| binding.into_any_element()),
3478            )
3479            .child(Label::new(button_text))
3480            .on_click(move |_event, cx| {
3481                focus_handle.dispatch_action(&Assist, cx);
3482            })
3483    }
3484
3485    fn active_workflow_step_for_cursor(&self, cx: &AppContext) -> Option<ActiveWorkflowStep> {
3486        let newest_cursor = self.editor.read(cx).selections.newest::<usize>(cx).head();
3487        let context = self.context.read(cx);
3488        let buffer = context.buffer().read(cx);
3489
3490        let workflow_steps = context.workflow_steps();
3491        workflow_steps
3492            .binary_search_by(|step| {
3493                let step_range = step.tagged_range.to_offset(&buffer);
3494                if newest_cursor < step_range.start {
3495                    Ordering::Greater
3496                } else if newest_cursor > step_range.end {
3497                    Ordering::Less
3498                } else {
3499                    Ordering::Equal
3500                }
3501            })
3502            .ok()
3503            .and_then(|index| {
3504                let range = workflow_steps[index].tagged_range.clone();
3505                Some(ActiveWorkflowStep {
3506                    resolved: self.workflow_steps.get(&range)?.resolved_step.is_some(),
3507                    range,
3508                })
3509            })
3510    }
3511}
3512
3513impl EventEmitter<EditorEvent> for ContextEditor {}
3514impl EventEmitter<SearchEvent> for ContextEditor {}
3515
3516impl Render for ContextEditor {
3517    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3518        let provider = LanguageModelRegistry::read_global(cx).active_provider();
3519        let accept_terms = if self.show_accept_terms {
3520            provider
3521                .as_ref()
3522                .and_then(|provider| provider.render_accept_terms(cx))
3523        } else {
3524            None
3525        };
3526
3527        v_flex()
3528            .key_context("ContextEditor")
3529            .capture_action(cx.listener(ContextEditor::cancel))
3530            .capture_action(cx.listener(ContextEditor::save))
3531            .capture_action(cx.listener(ContextEditor::copy))
3532            .capture_action(cx.listener(ContextEditor::cycle_message_role))
3533            .capture_action(cx.listener(ContextEditor::confirm_command))
3534            .on_action(cx.listener(ContextEditor::assist))
3535            .on_action(cx.listener(ContextEditor::split))
3536            .on_action(cx.listener(ContextEditor::debug_workflow_steps))
3537            .size_full()
3538            .children(self.render_notice(cx))
3539            .child(
3540                div()
3541                    .flex_grow()
3542                    .bg(cx.theme().colors().editor_background)
3543                    .child(self.editor.clone()),
3544            )
3545            .when_some(accept_terms, |this, element| {
3546                this.child(
3547                    div()
3548                        .absolute()
3549                        .right_4()
3550                        .bottom_10()
3551                        .max_w_96()
3552                        .py_2()
3553                        .px_3()
3554                        .elevation_2(cx)
3555                        .bg(cx.theme().colors().surface_background)
3556                        .occlude()
3557                        .child(element),
3558                )
3559            })
3560            .child(
3561                h_flex().flex_none().relative().child(
3562                    h_flex()
3563                        .w_full()
3564                        .absolute()
3565                        .right_4()
3566                        .bottom_2()
3567                        .justify_end()
3568                        .child(self.render_send_button(cx)),
3569                ),
3570            )
3571    }
3572}
3573
3574struct ErrorPopover {
3575    error: SharedString,
3576    focus_handle: FocusHandle,
3577}
3578
3579impl EventEmitter<DismissEvent> for ErrorPopover {}
3580
3581impl FocusableView for ErrorPopover {
3582    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
3583        self.focus_handle.clone()
3584    }
3585}
3586
3587impl Render for ErrorPopover {
3588    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3589        v_flex()
3590            .mt_2()
3591            .max_w_96()
3592            .py_2()
3593            .px_3()
3594            .gap_0p5()
3595            .elevation_2(cx)
3596            .bg(cx.theme().colors().surface_background)
3597            .occlude()
3598            .child(Label::new("Error interacting with language model").weight(FontWeight::SEMIBOLD))
3599            .child(Label::new(self.error.clone()))
3600            .child(
3601                h_flex().justify_end().mt_1().child(
3602                    Button::new("dismiss", "Dismiss")
3603                        .on_click(cx.listener(|_, _, cx| cx.emit(DismissEvent))),
3604                ),
3605            )
3606    }
3607}
3608
3609impl FocusableView for ContextEditor {
3610    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
3611        self.editor.focus_handle(cx)
3612    }
3613}
3614
3615impl Item for ContextEditor {
3616    type Event = editor::EditorEvent;
3617
3618    fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
3619        Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
3620    }
3621
3622    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
3623        match event {
3624            EditorEvent::Edited { .. } => {
3625                f(item::ItemEvent::Edit);
3626            }
3627            EditorEvent::TitleChanged => {
3628                f(item::ItemEvent::UpdateTab);
3629            }
3630            _ => {}
3631        }
3632    }
3633
3634    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
3635        Some(self.title(cx).to_string().into())
3636    }
3637
3638    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
3639        Some(Box::new(handle.clone()))
3640    }
3641
3642    fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
3643        self.editor.update(cx, |editor, cx| {
3644            Item::set_nav_history(editor, nav_history, cx)
3645        })
3646    }
3647
3648    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
3649        self.editor
3650            .update(cx, |editor, cx| Item::navigate(editor, data, cx))
3651    }
3652
3653    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
3654        self.editor
3655            .update(cx, |editor, cx| Item::deactivated(editor, cx))
3656    }
3657}
3658
3659impl SearchableItem for ContextEditor {
3660    type Match = <Editor as SearchableItem>::Match;
3661
3662    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
3663        self.editor.update(cx, |editor, cx| {
3664            editor.clear_matches(cx);
3665        });
3666    }
3667
3668    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
3669        self.editor
3670            .update(cx, |editor, cx| editor.update_matches(matches, cx));
3671    }
3672
3673    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
3674        self.editor
3675            .update(cx, |editor, cx| editor.query_suggestion(cx))
3676    }
3677
3678    fn activate_match(
3679        &mut self,
3680        index: usize,
3681        matches: &[Self::Match],
3682        cx: &mut ViewContext<Self>,
3683    ) {
3684        self.editor.update(cx, |editor, cx| {
3685            editor.activate_match(index, matches, cx);
3686        });
3687    }
3688
3689    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
3690        self.editor
3691            .update(cx, |editor, cx| editor.select_matches(matches, cx));
3692    }
3693
3694    fn replace(
3695        &mut self,
3696        identifier: &Self::Match,
3697        query: &project::search::SearchQuery,
3698        cx: &mut ViewContext<Self>,
3699    ) {
3700        self.editor
3701            .update(cx, |editor, cx| editor.replace(identifier, query, cx));
3702    }
3703
3704    fn find_matches(
3705        &mut self,
3706        query: Arc<project::search::SearchQuery>,
3707        cx: &mut ViewContext<Self>,
3708    ) -> Task<Vec<Self::Match>> {
3709        self.editor
3710            .update(cx, |editor, cx| editor.find_matches(query, cx))
3711    }
3712
3713    fn active_match_index(
3714        &mut self,
3715        matches: &[Self::Match],
3716        cx: &mut ViewContext<Self>,
3717    ) -> Option<usize> {
3718        self.editor
3719            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
3720    }
3721}
3722
3723impl FollowableItem for ContextEditor {
3724    fn remote_id(&self) -> Option<workspace::ViewId> {
3725        self.remote_id
3726    }
3727
3728    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
3729        let context = self.context.read(cx);
3730        Some(proto::view::Variant::ContextEditor(
3731            proto::view::ContextEditor {
3732                context_id: context.id().to_proto(),
3733                editor: if let Some(proto::view::Variant::Editor(proto)) =
3734                    self.editor.read(cx).to_state_proto(cx)
3735                {
3736                    Some(proto)
3737                } else {
3738                    None
3739                },
3740            },
3741        ))
3742    }
3743
3744    fn from_state_proto(
3745        workspace: View<Workspace>,
3746        id: workspace::ViewId,
3747        state: &mut Option<proto::view::Variant>,
3748        cx: &mut WindowContext,
3749    ) -> Option<Task<Result<View<Self>>>> {
3750        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
3751            return None;
3752        };
3753        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
3754            unreachable!()
3755        };
3756
3757        let context_id = ContextId::from_proto(state.context_id);
3758        let editor_state = state.editor?;
3759
3760        let (project, panel) = workspace.update(cx, |workspace, cx| {
3761            Some((
3762                workspace.project().clone(),
3763                workspace.panel::<AssistantPanel>(cx)?,
3764            ))
3765        })?;
3766
3767        let context_editor =
3768            panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
3769
3770        Some(cx.spawn(|mut cx| async move {
3771            let context_editor = context_editor.await?;
3772            context_editor
3773                .update(&mut cx, |context_editor, cx| {
3774                    context_editor.remote_id = Some(id);
3775                    context_editor.editor.update(cx, |editor, cx| {
3776                        editor.apply_update_proto(
3777                            &project,
3778                            proto::update_view::Variant::Editor(proto::update_view::Editor {
3779                                selections: editor_state.selections,
3780                                pending_selection: editor_state.pending_selection,
3781                                scroll_top_anchor: editor_state.scroll_top_anchor,
3782                                scroll_x: editor_state.scroll_y,
3783                                scroll_y: editor_state.scroll_y,
3784                                ..Default::default()
3785                            }),
3786                            cx,
3787                        )
3788                    })
3789                })?
3790                .await?;
3791            Ok(context_editor)
3792        }))
3793    }
3794
3795    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
3796        Editor::to_follow_event(event)
3797    }
3798
3799    fn add_event_to_update_proto(
3800        &self,
3801        event: &Self::Event,
3802        update: &mut Option<proto::update_view::Variant>,
3803        cx: &WindowContext,
3804    ) -> bool {
3805        self.editor
3806            .read(cx)
3807            .add_event_to_update_proto(event, update, cx)
3808    }
3809
3810    fn apply_update_proto(
3811        &mut self,
3812        project: &Model<Project>,
3813        message: proto::update_view::Variant,
3814        cx: &mut ViewContext<Self>,
3815    ) -> Task<Result<()>> {
3816        self.editor.update(cx, |editor, cx| {
3817            editor.apply_update_proto(project, message, cx)
3818        })
3819    }
3820
3821    fn is_project_item(&self, _cx: &WindowContext) -> bool {
3822        true
3823    }
3824
3825    fn set_leader_peer_id(
3826        &mut self,
3827        leader_peer_id: Option<proto::PeerId>,
3828        cx: &mut ViewContext<Self>,
3829    ) {
3830        self.editor.update(cx, |editor, cx| {
3831            editor.set_leader_peer_id(leader_peer_id, cx)
3832        })
3833    }
3834
3835    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
3836        if existing.context.read(cx).id() == self.context.read(cx).id() {
3837            Some(item::Dedup::KeepExisting)
3838        } else {
3839            None
3840        }
3841    }
3842}
3843
3844pub struct ContextEditorToolbarItem {
3845    fs: Arc<dyn Fs>,
3846    workspace: WeakView<Workspace>,
3847    active_context_editor: Option<WeakView<ContextEditor>>,
3848    model_summary_editor: View<Editor>,
3849}
3850
3851impl ContextEditorToolbarItem {
3852    pub fn new(
3853        workspace: &Workspace,
3854        _model_selector_menu_handle: PopoverMenuHandle<ContextMenu>,
3855        model_summary_editor: View<Editor>,
3856    ) -> Self {
3857        Self {
3858            fs: workspace.app_state().fs.clone(),
3859            workspace: workspace.weak_handle(),
3860            active_context_editor: None,
3861            model_summary_editor,
3862        }
3863    }
3864
3865    fn render_inject_context_menu(&self, cx: &mut ViewContext<Self>) -> impl Element {
3866        let commands = SlashCommandRegistry::global(cx);
3867        let active_editor_focus_handle = self.workspace.upgrade().and_then(|workspace| {
3868            Some(
3869                workspace
3870                    .read(cx)
3871                    .active_item_as::<Editor>(cx)?
3872                    .focus_handle(cx),
3873            )
3874        });
3875        let active_context_editor = self.active_context_editor.clone();
3876
3877        PopoverMenu::new("inject-context-menu")
3878            .trigger(IconButton::new("trigger", IconName::Quote).tooltip(|cx| {
3879                Tooltip::with_meta("Insert Context", None, "Type / to insert via keyboard", cx)
3880            }))
3881            .menu(move |cx| {
3882                let active_context_editor = active_context_editor.clone()?;
3883                ContextMenu::build(cx, |mut menu, _cx| {
3884                    for command_name in commands.featured_command_names() {
3885                        if let Some(command) = commands.command(&command_name) {
3886                            let menu_text = SharedString::from(Arc::from(command.menu_text()));
3887                            menu = menu.custom_entry(
3888                                {
3889                                    let command_name = command_name.clone();
3890                                    move |_cx| {
3891                                        h_flex()
3892                                            .gap_4()
3893                                            .w_full()
3894                                            .justify_between()
3895                                            .child(Label::new(menu_text.clone()))
3896                                            .child(
3897                                                Label::new(format!("/{command_name}"))
3898                                                    .color(Color::Muted),
3899                                            )
3900                                            .into_any()
3901                                    }
3902                                },
3903                                {
3904                                    let active_context_editor = active_context_editor.clone();
3905                                    move |cx| {
3906                                        active_context_editor
3907                                            .update(cx, |context_editor, cx| {
3908                                                context_editor.insert_command(&command_name, cx)
3909                                            })
3910                                            .ok();
3911                                    }
3912                                },
3913                            )
3914                        }
3915                    }
3916
3917                    if let Some(active_editor_focus_handle) = active_editor_focus_handle.clone() {
3918                        menu = menu
3919                            .context(active_editor_focus_handle)
3920                            .action("Quote Selection", Box::new(QuoteSelection));
3921                    }
3922
3923                    menu
3924                })
3925                .into()
3926            })
3927    }
3928
3929    fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
3930        let context = &self
3931            .active_context_editor
3932            .as_ref()?
3933            .upgrade()?
3934            .read(cx)
3935            .context;
3936        let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
3937            TokenState::NoTokensLeft {
3938                max_token_count,
3939                token_count,
3940            } => (Color::Error, token_count, max_token_count),
3941            TokenState::HasMoreTokens {
3942                max_token_count,
3943                token_count,
3944                over_warn_threshold,
3945            } => {
3946                let color = if over_warn_threshold {
3947                    Color::Warning
3948                } else {
3949                    Color::Muted
3950                };
3951                (color, token_count, max_token_count)
3952            }
3953        };
3954        Some(
3955            h_flex()
3956                .gap_0p5()
3957                .child(
3958                    Label::new(humanize_token_count(token_count))
3959                        .size(LabelSize::Small)
3960                        .color(token_count_color),
3961                )
3962                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
3963                .child(
3964                    Label::new(humanize_token_count(max_token_count))
3965                        .size(LabelSize::Small)
3966                        .color(Color::Muted),
3967                ),
3968        )
3969    }
3970}
3971
3972impl Render for ContextEditorToolbarItem {
3973    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3974        let left_side = h_flex()
3975            .gap_2()
3976            .flex_1()
3977            .min_w(rems(DEFAULT_TAB_TITLE.len() as f32))
3978            .when(self.active_context_editor.is_some(), |left_side| {
3979                left_side
3980                    .child(
3981                        IconButton::new("regenerate-context", IconName::ArrowCircle)
3982                            .visible_on_hover("toolbar")
3983                            .tooltip(|cx| Tooltip::text("Regenerate Summary", cx))
3984                            .on_click(cx.listener(move |_, _, cx| {
3985                                cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3986                            })),
3987                    )
3988                    .child(self.model_summary_editor.clone())
3989            });
3990        let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
3991        let active_model = LanguageModelRegistry::read_global(cx).active_model();
3992
3993        let right_side = h_flex()
3994            .gap_2()
3995            .child(ModelSelector::new(
3996                self.fs.clone(),
3997                ButtonLike::new("active-model")
3998                    .style(ButtonStyle::Subtle)
3999                    .child(
4000                        h_flex()
4001                            .w_full()
4002                            .gap_0p5()
4003                            .child(
4004                                div()
4005                                    .overflow_x_hidden()
4006                                    .flex_grow()
4007                                    .whitespace_nowrap()
4008                                    .child(match (active_provider, active_model) {
4009                                        (Some(provider), Some(model)) => h_flex()
4010                                            .gap_1()
4011                                            .child(
4012                                                Icon::new(provider.icon())
4013                                                    .color(Color::Muted)
4014                                                    .size(IconSize::XSmall),
4015                                            )
4016                                            .child(
4017                                                Label::new(model.name().0)
4018                                                    .size(LabelSize::Small)
4019                                                    .color(Color::Muted),
4020                                            )
4021                                            .into_any_element(),
4022                                        _ => Label::new("No model selected")
4023                                            .size(LabelSize::Small)
4024                                            .color(Color::Muted)
4025                                            .into_any_element(),
4026                                    }),
4027                            )
4028                            .child(
4029                                Icon::new(IconName::ChevronDown)
4030                                    .color(Color::Muted)
4031                                    .size(IconSize::XSmall),
4032                            ),
4033                    )
4034                    .tooltip(move |cx| {
4035                        Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
4036                    }),
4037            ))
4038            .children(self.render_remaining_tokens(cx))
4039            .child(self.render_inject_context_menu(cx));
4040
4041        h_flex()
4042            .size_full()
4043            .justify_between()
4044            .child(left_side)
4045            .child(right_side)
4046    }
4047}
4048
4049impl ToolbarItemView for ContextEditorToolbarItem {
4050    fn set_active_pane_item(
4051        &mut self,
4052        active_pane_item: Option<&dyn ItemHandle>,
4053        cx: &mut ViewContext<Self>,
4054    ) -> ToolbarItemLocation {
4055        self.active_context_editor = active_pane_item
4056            .and_then(|item| item.act_as::<ContextEditor>(cx))
4057            .map(|editor| editor.downgrade());
4058        cx.notify();
4059        if self.active_context_editor.is_none() {
4060            ToolbarItemLocation::Hidden
4061        } else {
4062            ToolbarItemLocation::PrimaryRight
4063        }
4064    }
4065
4066    fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
4067        cx.notify();
4068    }
4069}
4070
4071impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
4072
4073enum ContextEditorToolbarItemEvent {
4074    RegenerateSummary,
4075}
4076impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
4077
4078pub struct ContextHistory {
4079    picker: View<Picker<SavedContextPickerDelegate>>,
4080    _subscriptions: Vec<Subscription>,
4081    assistant_panel: WeakView<AssistantPanel>,
4082}
4083
4084impl ContextHistory {
4085    fn new(
4086        project: Model<Project>,
4087        context_store: Model<ContextStore>,
4088        assistant_panel: WeakView<AssistantPanel>,
4089        cx: &mut ViewContext<Self>,
4090    ) -> Self {
4091        let picker = cx.new_view(|cx| {
4092            Picker::uniform_list(
4093                SavedContextPickerDelegate::new(project, context_store.clone()),
4094                cx,
4095            )
4096            .modal(false)
4097            .max_height(None)
4098        });
4099
4100        let _subscriptions = vec![
4101            cx.observe(&context_store, |this, _, cx| {
4102                this.picker.update(cx, |picker, cx| picker.refresh(cx));
4103            }),
4104            cx.subscribe(&picker, Self::handle_picker_event),
4105        ];
4106
4107        Self {
4108            picker,
4109            _subscriptions,
4110            assistant_panel,
4111        }
4112    }
4113
4114    fn handle_picker_event(
4115        &mut self,
4116        _: View<Picker<SavedContextPickerDelegate>>,
4117        event: &SavedContextPickerEvent,
4118        cx: &mut ViewContext<Self>,
4119    ) {
4120        let SavedContextPickerEvent::Confirmed(context) = event;
4121        self.assistant_panel
4122            .update(cx, |assistant_panel, cx| match context {
4123                ContextMetadata::Remote(metadata) => {
4124                    assistant_panel
4125                        .open_remote_context(metadata.id.clone(), cx)
4126                        .detach_and_log_err(cx);
4127                }
4128                ContextMetadata::Saved(metadata) => {
4129                    assistant_panel
4130                        .open_saved_context(metadata.path.clone(), cx)
4131                        .detach_and_log_err(cx);
4132                }
4133            })
4134            .ok();
4135    }
4136}
4137
4138impl Render for ContextHistory {
4139    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
4140        div().size_full().child(self.picker.clone())
4141    }
4142}
4143
4144impl FocusableView for ContextHistory {
4145    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4146        self.picker.focus_handle(cx)
4147    }
4148}
4149
4150impl EventEmitter<()> for ContextHistory {}
4151
4152impl Item for ContextHistory {
4153    type Event = ();
4154
4155    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4156        Some("History".into())
4157    }
4158}
4159
4160pub struct ConfigurationView {
4161    focus_handle: FocusHandle,
4162    configuration_views: HashMap<LanguageModelProviderId, AnyView>,
4163    _registry_subscription: Subscription,
4164}
4165
4166impl ConfigurationView {
4167    fn new(cx: &mut ViewContext<Self>) -> Self {
4168        let focus_handle = cx.focus_handle();
4169
4170        let registry_subscription = cx.subscribe(
4171            &LanguageModelRegistry::global(cx),
4172            |this, _, event: &language_model::Event, cx| match event {
4173                language_model::Event::AddedProvider(provider_id) => {
4174                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
4175                    if let Some(provider) = provider {
4176                        this.add_configuration_view(&provider, cx);
4177                    }
4178                }
4179                language_model::Event::RemovedProvider(provider_id) => {
4180                    this.remove_configuration_view(provider_id);
4181                }
4182                _ => {}
4183            },
4184        );
4185
4186        let mut this = Self {
4187            focus_handle,
4188            configuration_views: HashMap::default(),
4189            _registry_subscription: registry_subscription,
4190        };
4191        this.build_configuration_views(cx);
4192        this
4193    }
4194
4195    fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
4196        let providers = LanguageModelRegistry::read_global(cx).providers();
4197        for provider in providers {
4198            self.add_configuration_view(&provider, cx);
4199        }
4200    }
4201
4202    fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
4203        self.configuration_views.remove(provider_id);
4204    }
4205
4206    fn add_configuration_view(
4207        &mut self,
4208        provider: &Arc<dyn LanguageModelProvider>,
4209        cx: &mut ViewContext<Self>,
4210    ) {
4211        let configuration_view = provider.configuration_view(cx);
4212        self.configuration_views
4213            .insert(provider.id(), configuration_view);
4214    }
4215
4216    fn render_provider_view(
4217        &mut self,
4218        provider: &Arc<dyn LanguageModelProvider>,
4219        cx: &mut ViewContext<Self>,
4220    ) -> Div {
4221        let provider_name = provider.name().0.clone();
4222        let configuration_view = self.configuration_views.get(&provider.id()).cloned();
4223
4224        let open_new_context = cx.listener({
4225            let provider = provider.clone();
4226            move |_, _, cx| {
4227                cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
4228                    provider.clone(),
4229                ))
4230            }
4231        });
4232
4233        v_flex()
4234            .gap_2()
4235            .child(
4236                h_flex()
4237                    .justify_between()
4238                    .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
4239                    .when(provider.is_authenticated(cx), move |this| {
4240                        this.child(
4241                            h_flex().justify_end().child(
4242                                Button::new("new-context", "Open new context")
4243                                    .icon_position(IconPosition::Start)
4244                                    .icon(IconName::Plus)
4245                                    .style(ButtonStyle::Filled)
4246                                    .layer(ElevationIndex::ModalSurface)
4247                                    .on_click(open_new_context),
4248                            ),
4249                        )
4250                    }),
4251            )
4252            .child(
4253                div()
4254                    .p(Spacing::Large.rems(cx))
4255                    .bg(cx.theme().colors().surface_background)
4256                    .border_1()
4257                    .border_color(cx.theme().colors().border_variant)
4258                    .rounded_md()
4259                    .when(configuration_view.is_none(), |this| {
4260                        this.child(div().child(Label::new(format!(
4261                            "No configuration view for {}",
4262                            provider_name
4263                        ))))
4264                    })
4265                    .when_some(configuration_view, |this, configuration_view| {
4266                        this.child(configuration_view)
4267                    }),
4268            )
4269    }
4270}
4271
4272impl Render for ConfigurationView {
4273    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4274        let providers = LanguageModelRegistry::read_global(cx).providers();
4275        let provider_views = providers
4276            .into_iter()
4277            .map(|provider| self.render_provider_view(&provider, cx))
4278            .collect::<Vec<_>>();
4279
4280        let mut element = v_flex()
4281            .id("assistant-configuration-view")
4282            .track_focus(&self.focus_handle)
4283            .bg(cx.theme().colors().editor_background)
4284            .size_full()
4285            .overflow_y_scroll()
4286            .child(
4287                v_flex()
4288                    .p(Spacing::XXLarge.rems(cx))
4289                    .border_b_1()
4290                    .border_color(cx.theme().colors().border)
4291                    .gap_1()
4292                    .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
4293                    .child(
4294                        Label::new(
4295                            "At least one LLM provider must be configured to use the Assistant.",
4296                        )
4297                        .color(Color::Muted),
4298                    ),
4299            )
4300            .child(
4301                v_flex()
4302                    .p(Spacing::XXLarge.rems(cx))
4303                    .mt_1()
4304                    .gap_6()
4305                    .flex_1()
4306                    .children(provider_views),
4307            )
4308            .into_any();
4309
4310        // We use a canvas here to get scrolling to work in the ConfigurationView. It's a workaround
4311        // because we couldn't the element to take up the size of the parent.
4312        canvas(
4313            move |bounds, cx| {
4314                element.prepaint_as_root(bounds.origin, bounds.size.into(), cx);
4315                element
4316            },
4317            |_, mut element, cx| {
4318                element.paint(cx);
4319            },
4320        )
4321        .flex_1()
4322        .w_full()
4323    }
4324}
4325
4326pub enum ConfigurationViewEvent {
4327    NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
4328}
4329
4330impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
4331
4332impl FocusableView for ConfigurationView {
4333    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
4334        self.focus_handle.clone()
4335    }
4336}
4337
4338impl Item for ConfigurationView {
4339    type Event = ConfigurationViewEvent;
4340
4341    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4342        Some("Configuration".into())
4343    }
4344}
4345
4346type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
4347
4348fn render_slash_command_output_toggle(
4349    row: MultiBufferRow,
4350    is_folded: bool,
4351    fold: ToggleFold,
4352    _cx: &mut WindowContext,
4353) -> AnyElement {
4354    Disclosure::new(
4355        ("slash-command-output-fold-indicator", row.0 as u64),
4356        !is_folded,
4357    )
4358    .selected(is_folded)
4359    .on_click(move |_e, cx| fold(!is_folded, cx))
4360    .into_any_element()
4361}
4362
4363fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) -> FoldPlaceholder {
4364    FoldPlaceholder {
4365        render: Arc::new({
4366            move |fold_id, fold_range, _cx| {
4367                let editor = editor.clone();
4368                ButtonLike::new(fold_id)
4369                    .style(ButtonStyle::Filled)
4370                    .layer(ElevationIndex::ElevatedSurface)
4371                    .child(Icon::new(IconName::FileText))
4372                    .child(Label::new(title.clone()).single_line())
4373                    .on_click(move |_, cx| {
4374                        editor
4375                            .update(cx, |editor, cx| {
4376                                let buffer_start = fold_range
4377                                    .start
4378                                    .to_point(&editor.buffer().read(cx).read(cx));
4379                                let buffer_row = MultiBufferRow(buffer_start.row);
4380                                editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4381                            })
4382                            .ok();
4383                    })
4384                    .into_any_element()
4385            }
4386        }),
4387        constrain_width: false,
4388        merge_adjacent: false,
4389    }
4390}
4391
4392fn render_quote_selection_output_toggle(
4393    row: MultiBufferRow,
4394    is_folded: bool,
4395    fold: ToggleFold,
4396    _cx: &mut WindowContext,
4397) -> AnyElement {
4398    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
4399        .selected(is_folded)
4400        .on_click(move |_e, cx| fold(!is_folded, cx))
4401        .into_any_element()
4402}
4403
4404fn render_pending_slash_command_gutter_decoration(
4405    row: MultiBufferRow,
4406    status: &PendingSlashCommandStatus,
4407    confirm_command: Arc<dyn Fn(&mut WindowContext)>,
4408) -> AnyElement {
4409    let mut icon = IconButton::new(
4410        ("slash-command-gutter-decoration", row.0),
4411        ui::IconName::TriangleRight,
4412    )
4413    .on_click(move |_e, cx| confirm_command(cx))
4414    .icon_size(ui::IconSize::Small)
4415    .size(ui::ButtonSize::None);
4416
4417    match status {
4418        PendingSlashCommandStatus::Idle => {
4419            icon = icon.icon_color(Color::Muted);
4420        }
4421        PendingSlashCommandStatus::Running { .. } => {
4422            icon = icon.selected(true);
4423        }
4424        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
4425    }
4426
4427    icon.into_any_element()
4428}
4429
4430fn render_docs_slash_command_trailer(
4431    row: MultiBufferRow,
4432    command: PendingSlashCommand,
4433    cx: &mut WindowContext,
4434) -> AnyElement {
4435    let Some(argument) = command.argument else {
4436        return Empty.into_any();
4437    };
4438
4439    let args = DocsSlashCommandArgs::parse(&argument);
4440
4441    let Some(store) = args
4442        .provider()
4443        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
4444    else {
4445        return Empty.into_any();
4446    };
4447
4448    let Some(package) = args.package() else {
4449        return Empty.into_any();
4450    };
4451
4452    let mut children = Vec::new();
4453
4454    if store.is_indexing(&package) {
4455        children.push(
4456            div()
4457                .id(("crates-being-indexed", row.0))
4458                .child(Icon::new(IconName::ArrowCircle).with_animation(
4459                    "arrow-circle",
4460                    Animation::new(Duration::from_secs(4)).repeat(),
4461                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
4462                ))
4463                .tooltip({
4464                    let package = package.clone();
4465                    move |cx| Tooltip::text(format!("Indexing {package}"), cx)
4466                })
4467                .into_any_element(),
4468        );
4469    }
4470
4471    if let Some(latest_error) = store.latest_error_for_package(&package) {
4472        children.push(
4473            div()
4474                .id(("latest-error", row.0))
4475                .child(
4476                    Icon::new(IconName::ExclamationTriangle)
4477                        .size(IconSize::Small)
4478                        .color(Color::Warning),
4479                )
4480                .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
4481                .into_any_element(),
4482        )
4483    }
4484
4485    let is_indexing = store.is_indexing(&package);
4486    let latest_error = store.latest_error_for_package(&package);
4487
4488    if !is_indexing && latest_error.is_none() {
4489        return Empty.into_any();
4490    }
4491
4492    h_flex().gap_2().children(children).into_any_element()
4493}
4494
4495fn make_lsp_adapter_delegate(
4496    project: &Model<Project>,
4497    cx: &mut AppContext,
4498) -> Result<Arc<dyn LspAdapterDelegate>> {
4499    project.update(cx, |project, cx| {
4500        // TODO: Find the right worktree.
4501        let worktree = project
4502            .worktrees(cx)
4503            .next()
4504            .ok_or_else(|| anyhow!("no worktrees when constructing ProjectLspAdapterDelegate"))?;
4505        Ok(ProjectLspAdapterDelegate::new(project, &worktree, cx) as Arc<dyn LspAdapterDelegate>)
4506    })
4507}
4508
4509fn slash_command_error_block_renderer(message: String) -> RenderBlock {
4510    Box::new(move |_| {
4511        div()
4512            .pl_6()
4513            .child(
4514                Label::new(format!("error: {}", message))
4515                    .single_line()
4516                    .color(Color::Error),
4517            )
4518            .into_any()
4519    })
4520}
4521
4522enum TokenState {
4523    NoTokensLeft {
4524        max_token_count: usize,
4525        token_count: usize,
4526    },
4527    HasMoreTokens {
4528        max_token_count: usize,
4529        token_count: usize,
4530        over_warn_threshold: bool,
4531    },
4532}
4533
4534fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
4535    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
4536
4537    let model = LanguageModelRegistry::read_global(cx).active_model()?;
4538    let token_count = context.read(cx).token_count()?;
4539    let max_token_count = model.max_token_count();
4540
4541    let remaining_tokens = max_token_count as isize - token_count as isize;
4542    let token_state = if remaining_tokens <= 0 {
4543        TokenState::NoTokensLeft {
4544            max_token_count,
4545            token_count,
4546        }
4547    } else {
4548        let over_warn_threshold =
4549            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
4550        TokenState::HasMoreTokens {
4551            max_token_count,
4552            token_count,
4553            over_warn_threshold,
4554        }
4555    };
4556    Some(token_state)
4557}
4558
4559enum ConfigurationError {
4560    NoProvider,
4561    ProviderNotAuthenticated,
4562}
4563
4564fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
4565    let provider = LanguageModelRegistry::read_global(cx).active_provider();
4566    let is_authenticated = provider
4567        .as_ref()
4568        .map_or(false, |provider| provider.is_authenticated(cx));
4569
4570    if provider.is_some() && is_authenticated {
4571        return None;
4572    }
4573
4574    if provider.is_none() {
4575        return Some(ConfigurationError::NoProvider);
4576    }
4577
4578    if !is_authenticated {
4579        return Some(ConfigurationError::ProviderNotAuthenticated);
4580    }
4581
4582    None
4583}