assistant_panel.rs

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