assistant_panel.rs

   1use std::path::PathBuf;
   2use std::sync::Arc;
   3
   4use anyhow::{anyhow, Result};
   5use assistant_context_editor::{
   6    make_lsp_adapter_delegate, AssistantPanelDelegate, ConfigurationError, ContextEditor,
   7    ContextHistory, SlashCommandCompletionProvider,
   8};
   9use assistant_settings::{AssistantDockPosition, AssistantSettings};
  10use assistant_slash_command::SlashCommandWorkingSet;
  11use assistant_tool::ToolWorkingSet;
  12
  13use client::zed_urls;
  14use editor::Editor;
  15use fs::Fs;
  16use gpui::{
  17    prelude::*, px, svg, Action, AnyElement, App, AsyncWindowContext, Corner, Entity, EventEmitter,
  18    FocusHandle, Focusable, FontWeight, Pixels, Subscription, Task, UpdateGlobal, WeakEntity,
  19};
  20use language::LanguageRegistry;
  21use language_model::{LanguageModelProviderTosView, LanguageModelRegistry};
  22use project::Project;
  23use prompt_library::{open_prompt_library, PromptBuilder, PromptLibrary};
  24use settings::{update_settings_file, Settings};
  25use time::UtcOffset;
  26use ui::{prelude::*, ContextMenu, KeyBinding, PopoverMenu, PopoverMenuHandle, Tab, Tooltip};
  27use util::ResultExt as _;
  28use workspace::dock::{DockPosition, Panel, PanelEvent};
  29use workspace::Workspace;
  30use zed_actions::assistant::{DeployPromptLibrary, ToggleFocus};
  31
  32use crate::active_thread::ActiveThread;
  33use crate::assistant_configuration::{AssistantConfiguration, AssistantConfigurationEvent};
  34use crate::message_editor::MessageEditor;
  35use crate::thread::{Thread, ThreadError, ThreadId};
  36use crate::thread_history::{PastThread, ThreadHistory};
  37use crate::thread_store::ThreadStore;
  38use crate::{
  39    InlineAssistant, NewPromptEditor, NewThread, OpenConfiguration, OpenHistory,
  40    OpenPromptEditorHistory,
  41};
  42
  43pub fn init(cx: &mut App) {
  44    cx.observe_new(
  45        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
  46            workspace
  47                .register_action(|workspace, _: &NewThread, window, cx| {
  48                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  49                        panel.update(cx, |panel, cx| panel.new_thread(window, cx));
  50                        workspace.focus_panel::<AssistantPanel>(window, cx);
  51                    }
  52                })
  53                .register_action(|workspace, _: &OpenHistory, window, cx| {
  54                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  55                        workspace.focus_panel::<AssistantPanel>(window, cx);
  56                        panel.update(cx, |panel, cx| panel.open_history(window, cx));
  57                    }
  58                })
  59                .register_action(|workspace, _: &NewPromptEditor, window, cx| {
  60                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  61                        workspace.focus_panel::<AssistantPanel>(window, cx);
  62                        panel.update(cx, |panel, cx| panel.new_prompt_editor(window, cx));
  63                    }
  64                })
  65                .register_action(|workspace, _: &OpenPromptEditorHistory, window, cx| {
  66                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  67                        workspace.focus_panel::<AssistantPanel>(window, cx);
  68                        panel.update(cx, |panel, cx| panel.open_prompt_editor_history(window, cx));
  69                    }
  70                })
  71                .register_action(|workspace, _: &OpenConfiguration, window, cx| {
  72                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  73                        workspace.focus_panel::<AssistantPanel>(window, cx);
  74                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
  75                    }
  76                });
  77        },
  78    )
  79    .detach();
  80}
  81
  82enum ActiveView {
  83    Thread,
  84    PromptEditor,
  85    History,
  86    PromptEditorHistory,
  87    Configuration,
  88}
  89
  90pub struct AssistantPanel {
  91    workspace: WeakEntity<Workspace>,
  92    project: Entity<Project>,
  93    fs: Arc<dyn Fs>,
  94    language_registry: Arc<LanguageRegistry>,
  95    thread_store: Entity<ThreadStore>,
  96    thread: Entity<ActiveThread>,
  97    message_editor: Entity<MessageEditor>,
  98    context_store: Entity<assistant_context_editor::ContextStore>,
  99    context_editor: Option<Entity<ContextEditor>>,
 100    context_history: Option<Entity<ContextHistory>>,
 101    configuration: Option<Entity<AssistantConfiguration>>,
 102    configuration_subscription: Option<Subscription>,
 103    tools: Arc<ToolWorkingSet>,
 104    local_timezone: UtcOffset,
 105    active_view: ActiveView,
 106    history: Entity<ThreadHistory>,
 107    new_item_context_menu_handle: PopoverMenuHandle<ContextMenu>,
 108    open_history_context_menu_handle: PopoverMenuHandle<ContextMenu>,
 109    width: Option<Pixels>,
 110    height: Option<Pixels>,
 111}
 112
 113impl AssistantPanel {
 114    pub fn load(
 115        workspace: WeakEntity<Workspace>,
 116        prompt_builder: Arc<PromptBuilder>,
 117        cx: AsyncWindowContext,
 118    ) -> Task<Result<Entity<Self>>> {
 119        cx.spawn(|mut cx| async move {
 120            let tools = Arc::new(ToolWorkingSet::default());
 121            log::info!("[assistant2-debug] initializing ThreadStore");
 122            let thread_store = workspace.update(&mut cx, |workspace, cx| {
 123                let project = workspace.project().clone();
 124                ThreadStore::new(project, tools.clone(), cx)
 125            })??;
 126            log::info!("[assistant2-debug] finished initializing ThreadStore");
 127
 128            let slash_commands = Arc::new(SlashCommandWorkingSet::default());
 129            log::info!("[assistant2-debug] initializing ContextStore");
 130            let context_store = workspace
 131                .update(&mut cx, |workspace, cx| {
 132                    let project = workspace.project().clone();
 133                    assistant_context_editor::ContextStore::new(
 134                        project,
 135                        prompt_builder.clone(),
 136                        slash_commands,
 137                        cx,
 138                    )
 139                })?
 140                .await?;
 141            log::info!("[assistant2-debug] finished initializing ContextStore");
 142
 143            workspace.update_in(&mut cx, |workspace, window, cx| {
 144                cx.new(|cx| Self::new(workspace, thread_store, context_store, tools, window, cx))
 145            })
 146        })
 147    }
 148
 149    fn new(
 150        workspace: &Workspace,
 151        thread_store: Entity<ThreadStore>,
 152        context_store: Entity<assistant_context_editor::ContextStore>,
 153        tools: Arc<ToolWorkingSet>,
 154        window: &mut Window,
 155        cx: &mut Context<Self>,
 156    ) -> Self {
 157        log::info!("[assistant2-debug] AssistantPanel::new");
 158        let thread = thread_store.update(cx, |this, cx| this.create_thread(cx));
 159        let fs = workspace.app_state().fs.clone();
 160        let project = workspace.project().clone();
 161        let language_registry = project.read(cx).languages().clone();
 162        let workspace = workspace.weak_handle();
 163        let weak_self = cx.entity().downgrade();
 164
 165        let message_editor = cx.new(|cx| {
 166            MessageEditor::new(
 167                fs.clone(),
 168                workspace.clone(),
 169                thread_store.downgrade(),
 170                thread.clone(),
 171                window,
 172                cx,
 173            )
 174        });
 175
 176        Self {
 177            active_view: ActiveView::Thread,
 178            workspace: workspace.clone(),
 179            project,
 180            fs: fs.clone(),
 181            language_registry: language_registry.clone(),
 182            thread_store: thread_store.clone(),
 183            thread: cx.new(|cx| {
 184                ActiveThread::new(
 185                    thread.clone(),
 186                    thread_store.clone(),
 187                    workspace,
 188                    language_registry,
 189                    tools.clone(),
 190                    window,
 191                    cx,
 192                )
 193            }),
 194            message_editor,
 195            context_store,
 196            context_editor: None,
 197            context_history: None,
 198            configuration: None,
 199            configuration_subscription: None,
 200            tools,
 201            local_timezone: UtcOffset::from_whole_seconds(
 202                chrono::Local::now().offset().local_minus_utc(),
 203            )
 204            .unwrap(),
 205            history: cx.new(|cx| ThreadHistory::new(weak_self, thread_store, cx)),
 206            new_item_context_menu_handle: PopoverMenuHandle::default(),
 207            open_history_context_menu_handle: PopoverMenuHandle::default(),
 208            width: None,
 209            height: None,
 210        }
 211    }
 212
 213    pub fn toggle_focus(
 214        workspace: &mut Workspace,
 215        _: &ToggleFocus,
 216        window: &mut Window,
 217        cx: &mut Context<Workspace>,
 218    ) {
 219        let settings = AssistantSettings::get_global(cx);
 220        if !settings.enabled {
 221            return;
 222        }
 223
 224        workspace.toggle_panel_focus::<Self>(window, cx);
 225    }
 226
 227    pub(crate) fn local_timezone(&self) -> UtcOffset {
 228        self.local_timezone
 229    }
 230
 231    pub(crate) fn thread_store(&self) -> &Entity<ThreadStore> {
 232        &self.thread_store
 233    }
 234
 235    fn cancel(
 236        &mut self,
 237        _: &editor::actions::Cancel,
 238        _window: &mut Window,
 239        cx: &mut Context<Self>,
 240    ) {
 241        self.thread
 242            .update(cx, |thread, cx| thread.cancel_last_completion(cx));
 243    }
 244
 245    fn new_thread(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 246        let thread = self
 247            .thread_store
 248            .update(cx, |this, cx| this.create_thread(cx));
 249
 250        self.active_view = ActiveView::Thread;
 251        self.thread = cx.new(|cx| {
 252            ActiveThread::new(
 253                thread.clone(),
 254                self.thread_store.clone(),
 255                self.workspace.clone(),
 256                self.language_registry.clone(),
 257                self.tools.clone(),
 258                window,
 259                cx,
 260            )
 261        });
 262        self.message_editor = cx.new(|cx| {
 263            MessageEditor::new(
 264                self.fs.clone(),
 265                self.workspace.clone(),
 266                self.thread_store.downgrade(),
 267                thread,
 268                window,
 269                cx,
 270            )
 271        });
 272        self.message_editor.focus_handle(cx).focus(window);
 273    }
 274
 275    fn new_prompt_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 276        self.active_view = ActiveView::PromptEditor;
 277
 278        let context = self
 279            .context_store
 280            .update(cx, |context_store, cx| context_store.create(cx));
 281        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
 282            .log_err()
 283            .flatten();
 284
 285        self.context_editor = Some(cx.new(|cx| {
 286            let mut editor = ContextEditor::for_context(
 287                context,
 288                self.fs.clone(),
 289                self.workspace.clone(),
 290                self.project.clone(),
 291                lsp_adapter_delegate,
 292                window,
 293                cx,
 294            );
 295            editor.insert_default_prompt(window, cx);
 296            editor
 297        }));
 298
 299        if let Some(context_editor) = self.context_editor.as_ref() {
 300            context_editor.focus_handle(cx).focus(window);
 301        }
 302    }
 303
 304    fn deploy_prompt_library(
 305        &mut self,
 306        _: &DeployPromptLibrary,
 307        _window: &mut Window,
 308        cx: &mut Context<Self>,
 309    ) {
 310        open_prompt_library(
 311            self.language_registry.clone(),
 312            Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
 313            Arc::new(|| {
 314                Box::new(SlashCommandCompletionProvider::new(
 315                    Arc::new(SlashCommandWorkingSet::default()),
 316                    None,
 317                    None,
 318                ))
 319            }),
 320            cx,
 321        )
 322        .detach_and_log_err(cx);
 323    }
 324
 325    fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 326        self.active_view = ActiveView::History;
 327        self.history.focus_handle(cx).focus(window);
 328        cx.notify();
 329    }
 330
 331    fn open_prompt_editor_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 332        self.active_view = ActiveView::PromptEditorHistory;
 333        self.context_history = Some(cx.new(|cx| {
 334            ContextHistory::new(
 335                self.project.clone(),
 336                self.context_store.clone(),
 337                self.workspace.clone(),
 338                window,
 339                cx,
 340            )
 341        }));
 342
 343        if let Some(context_history) = self.context_history.as_ref() {
 344            context_history.focus_handle(cx).focus(window);
 345        }
 346
 347        cx.notify();
 348    }
 349
 350    fn open_saved_prompt_editor(
 351        &mut self,
 352        path: PathBuf,
 353        window: &mut Window,
 354        cx: &mut Context<Self>,
 355    ) -> Task<Result<()>> {
 356        let context = self
 357            .context_store
 358            .update(cx, |store, cx| store.open_local_context(path.clone(), cx));
 359        let fs = self.fs.clone();
 360        let project = self.project.clone();
 361        let workspace = self.workspace.clone();
 362
 363        let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err().flatten();
 364
 365        cx.spawn_in(window, |this, mut cx| async move {
 366            let context = context.await?;
 367            this.update_in(&mut cx, |this, window, cx| {
 368                let editor = cx.new(|cx| {
 369                    ContextEditor::for_context(
 370                        context,
 371                        fs,
 372                        workspace,
 373                        project,
 374                        lsp_adapter_delegate,
 375                        window,
 376                        cx,
 377                    )
 378                });
 379                this.active_view = ActiveView::PromptEditor;
 380                this.context_editor = Some(editor);
 381
 382                anyhow::Ok(())
 383            })??;
 384            Ok(())
 385        })
 386    }
 387
 388    pub(crate) fn open_thread(
 389        &mut self,
 390        thread_id: &ThreadId,
 391        window: &mut Window,
 392        cx: &mut Context<Self>,
 393    ) -> Task<Result<()>> {
 394        let open_thread_task = self
 395            .thread_store
 396            .update(cx, |this, cx| this.open_thread(thread_id, cx));
 397
 398        cx.spawn_in(window, |this, mut cx| async move {
 399            let thread = open_thread_task.await?;
 400            this.update_in(&mut cx, |this, window, cx| {
 401                this.active_view = ActiveView::Thread;
 402                this.thread = cx.new(|cx| {
 403                    ActiveThread::new(
 404                        thread.clone(),
 405                        this.thread_store.clone(),
 406                        this.workspace.clone(),
 407                        this.language_registry.clone(),
 408                        this.tools.clone(),
 409                        window,
 410                        cx,
 411                    )
 412                });
 413                this.message_editor = cx.new(|cx| {
 414                    MessageEditor::new(
 415                        this.fs.clone(),
 416                        this.workspace.clone(),
 417                        this.thread_store.downgrade(),
 418                        thread,
 419                        window,
 420                        cx,
 421                    )
 422                });
 423                this.message_editor.focus_handle(cx).focus(window);
 424            })
 425        })
 426    }
 427
 428    pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 429        self.active_view = ActiveView::Configuration;
 430        self.configuration = Some(cx.new(|cx| AssistantConfiguration::new(window, cx)));
 431
 432        if let Some(configuration) = self.configuration.as_ref() {
 433            self.configuration_subscription = Some(cx.subscribe_in(
 434                configuration,
 435                window,
 436                Self::handle_assistant_configuration_event,
 437            ));
 438
 439            configuration.focus_handle(cx).focus(window);
 440        }
 441    }
 442
 443    fn handle_assistant_configuration_event(
 444        &mut self,
 445        _entity: &Entity<AssistantConfiguration>,
 446        event: &AssistantConfigurationEvent,
 447        window: &mut Window,
 448        cx: &mut Context<Self>,
 449    ) {
 450        match event {
 451            AssistantConfigurationEvent::NewThread(provider) => {
 452                if LanguageModelRegistry::read_global(cx)
 453                    .active_provider()
 454                    .map_or(true, |active_provider| {
 455                        active_provider.id() != provider.id()
 456                    })
 457                {
 458                    if let Some(model) = provider.provided_models(cx).first().cloned() {
 459                        update_settings_file::<AssistantSettings>(
 460                            self.fs.clone(),
 461                            cx,
 462                            move |settings, _| settings.set_model(model),
 463                        );
 464                    }
 465                }
 466
 467                self.new_thread(window, cx);
 468            }
 469        }
 470    }
 471
 472    pub(crate) fn active_thread(&self, cx: &App) -> Entity<Thread> {
 473        self.thread.read(cx).thread().clone()
 474    }
 475
 476    pub(crate) fn delete_thread(&mut self, thread_id: &ThreadId, cx: &mut Context<Self>) {
 477        self.thread_store
 478            .update(cx, |this, cx| this.delete_thread(thread_id, cx))
 479            .detach_and_log_err(cx);
 480    }
 481}
 482
 483impl Focusable for AssistantPanel {
 484    fn focus_handle(&self, cx: &App) -> FocusHandle {
 485        match self.active_view {
 486            ActiveView::Thread => self.message_editor.focus_handle(cx),
 487            ActiveView::History => self.history.focus_handle(cx),
 488            ActiveView::PromptEditor => {
 489                if let Some(context_editor) = self.context_editor.as_ref() {
 490                    context_editor.focus_handle(cx)
 491                } else {
 492                    cx.focus_handle()
 493                }
 494            }
 495            ActiveView::PromptEditorHistory => {
 496                if let Some(context_history) = self.context_history.as_ref() {
 497                    context_history.focus_handle(cx)
 498                } else {
 499                    cx.focus_handle()
 500                }
 501            }
 502            ActiveView::Configuration => {
 503                if let Some(configuration) = self.configuration.as_ref() {
 504                    configuration.focus_handle(cx)
 505                } else {
 506                    cx.focus_handle()
 507                }
 508            }
 509        }
 510    }
 511}
 512
 513impl EventEmitter<PanelEvent> for AssistantPanel {}
 514
 515impl Panel for AssistantPanel {
 516    fn persistent_name() -> &'static str {
 517        "AssistantPanel2"
 518    }
 519
 520    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
 521        match AssistantSettings::get_global(cx).dock {
 522            AssistantDockPosition::Left => DockPosition::Left,
 523            AssistantDockPosition::Bottom => DockPosition::Bottom,
 524            AssistantDockPosition::Right => DockPosition::Right,
 525        }
 526    }
 527
 528    fn position_is_valid(&self, _: DockPosition) -> bool {
 529        true
 530    }
 531
 532    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
 533        settings::update_settings_file::<AssistantSettings>(
 534            self.fs.clone(),
 535            cx,
 536            move |settings, _| {
 537                let dock = match position {
 538                    DockPosition::Left => AssistantDockPosition::Left,
 539                    DockPosition::Bottom => AssistantDockPosition::Bottom,
 540                    DockPosition::Right => AssistantDockPosition::Right,
 541                };
 542                settings.set_dock(dock);
 543            },
 544        );
 545    }
 546
 547    fn size(&self, window: &Window, cx: &App) -> Pixels {
 548        let settings = AssistantSettings::get_global(cx);
 549        match self.position(window, cx) {
 550            DockPosition::Left | DockPosition::Right => {
 551                self.width.unwrap_or(settings.default_width)
 552            }
 553            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
 554        }
 555    }
 556
 557    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
 558        match self.position(window, cx) {
 559            DockPosition::Left | DockPosition::Right => self.width = size,
 560            DockPosition::Bottom => self.height = size,
 561        }
 562        cx.notify();
 563    }
 564
 565    fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
 566
 567    fn remote_id() -> Option<proto::PanelId> {
 568        Some(proto::PanelId::AssistantPanel)
 569    }
 570
 571    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
 572        let settings = AssistantSettings::get_global(cx);
 573        if !settings.enabled || !settings.button {
 574            return None;
 575        }
 576
 577        Some(IconName::ZedAssistant)
 578    }
 579
 580    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
 581        Some("Assistant Panel")
 582    }
 583
 584    fn toggle_action(&self) -> Box<dyn Action> {
 585        Box::new(ToggleFocus)
 586    }
 587
 588    fn activation_priority(&self) -> u32 {
 589        3
 590    }
 591}
 592
 593impl AssistantPanel {
 594    fn render_toolbar(&self, cx: &mut Context<Self>) -> impl IntoElement {
 595        let thread = self.thread.read(cx);
 596
 597        let title = match self.active_view {
 598            ActiveView::Thread => {
 599                if thread.is_empty() {
 600                    thread.summary_or_default(cx)
 601                } else {
 602                    thread
 603                        .summary(cx)
 604                        .unwrap_or_else(|| SharedString::from("Loading Summary…"))
 605                }
 606            }
 607            ActiveView::PromptEditor => self
 608                .context_editor
 609                .as_ref()
 610                .map(|context_editor| {
 611                    SharedString::from(context_editor.read(cx).title(cx).to_string())
 612                })
 613                .unwrap_or_else(|| SharedString::from("Loading Summary…")),
 614            ActiveView::History | ActiveView::PromptEditorHistory => "History".into(),
 615            ActiveView::Configuration => "Assistant Settings".into(),
 616        };
 617
 618        let sub_title = match self.active_view {
 619            ActiveView::Thread => None,
 620            ActiveView::PromptEditor => None,
 621            ActiveView::History => Some("Thread"),
 622            ActiveView::PromptEditorHistory => Some("Prompt Editor"),
 623            ActiveView::Configuration => None,
 624        };
 625
 626        h_flex()
 627            .id("assistant-toolbar")
 628            .px(DynamicSpacing::Base08.rems(cx))
 629            .h(Tab::container_height(cx))
 630            .flex_none()
 631            .justify_between()
 632            .gap(DynamicSpacing::Base08.rems(cx))
 633            .bg(cx.theme().colors().tab_bar_background)
 634            .border_b_1()
 635            .border_color(cx.theme().colors().border)
 636            .child(
 637                h_flex()
 638                    .child(Label::new(title))
 639                    .when(sub_title.is_some(), |this| {
 640                        this.child(
 641                            h_flex()
 642                                .pl_1p5()
 643                                .gap_1p5()
 644                                .child(
 645                                    Label::new("/")
 646                                        .size(LabelSize::Small)
 647                                        .color(Color::Disabled)
 648                                        .alpha(0.5),
 649                                )
 650                                .child(Label::new(sub_title.unwrap())),
 651                        )
 652                    }),
 653            )
 654            .child(
 655                h_flex()
 656                    .h_full()
 657                    .pl_1p5()
 658                    .border_l_1()
 659                    .border_color(cx.theme().colors().border)
 660                    .gap(DynamicSpacing::Base02.rems(cx))
 661                    .child(
 662                        PopoverMenu::new("assistant-toolbar-new-popover-menu")
 663                            .trigger_with_tooltip(
 664                                IconButton::new("new", IconName::Plus)
 665                                    .icon_size(IconSize::Small)
 666                                    .style(ButtonStyle::Subtle),
 667                                Tooltip::text("New…"),
 668                            )
 669                            .anchor(Corner::TopRight)
 670                            .with_handle(self.new_item_context_menu_handle.clone())
 671                            .menu(move |window, cx| {
 672                                Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 673                                    menu.action("New Thread", NewThread.boxed_clone())
 674                                        .action("New Prompt Editor", NewPromptEditor.boxed_clone())
 675                                }))
 676                            }),
 677                    )
 678                    .child(
 679                        PopoverMenu::new("assistant-toolbar-history-popover-menu")
 680                            .trigger_with_tooltip(
 681                                IconButton::new("open-history", IconName::HistoryRerun)
 682                                    .icon_size(IconSize::Small)
 683                                    .style(ButtonStyle::Subtle),
 684                                Tooltip::text("History…"),
 685                            )
 686                            .anchor(Corner::TopRight)
 687                            .with_handle(self.open_history_context_menu_handle.clone())
 688                            .menu(move |window, cx| {
 689                                Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 690                                    menu.action("Thread History", OpenHistory.boxed_clone())
 691                                        .action(
 692                                            "Prompt Editor History",
 693                                            OpenPromptEditorHistory.boxed_clone(),
 694                                        )
 695                                }))
 696                            }),
 697                    )
 698                    .child(
 699                        IconButton::new("configure-assistant", IconName::Settings)
 700                            .icon_size(IconSize::Small)
 701                            .style(ButtonStyle::Subtle)
 702                            .tooltip(Tooltip::text("Assistant Settings"))
 703                            .on_click(move |_event, window, cx| {
 704                                window.dispatch_action(OpenConfiguration.boxed_clone(), cx);
 705                            }),
 706                    ),
 707            )
 708    }
 709
 710    fn render_active_thread_or_empty_state(
 711        &self,
 712        window: &mut Window,
 713        cx: &mut Context<Self>,
 714    ) -> AnyElement {
 715        if self.thread.read(cx).is_empty() {
 716            return self
 717                .render_thread_empty_state(window, cx)
 718                .into_any_element();
 719        }
 720
 721        self.thread.clone().into_any_element()
 722    }
 723
 724    fn configuration_error(&self, cx: &App) -> Option<ConfigurationError> {
 725        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
 726            return Some(ConfigurationError::NoProvider);
 727        };
 728
 729        if !provider.is_authenticated(cx) {
 730            return Some(ConfigurationError::ProviderNotAuthenticated);
 731        }
 732
 733        if provider.must_accept_terms(cx) {
 734            return Some(ConfigurationError::ProviderPendingTermsAcceptance(provider));
 735        }
 736
 737        None
 738    }
 739
 740    fn render_thread_empty_state(
 741        &self,
 742        window: &mut Window,
 743        cx: &mut Context<Self>,
 744    ) -> impl IntoElement {
 745        let recent_threads = self
 746            .thread_store
 747            .update(cx, |this, _cx| this.recent_threads(3));
 748
 749        let create_welcome_heading = || {
 750            h_flex()
 751                .w_full()
 752                .justify_center()
 753                .child(Headline::new("Welcome to the Assistant Panel").size(HeadlineSize::Small))
 754        };
 755
 756        let configuration_error = self.configuration_error(cx);
 757        let no_error = configuration_error.is_none();
 758
 759        v_flex()
 760            .gap_2()
 761            .child(
 762                v_flex().w_full().child(
 763                    svg()
 764                        .path("icons/logo_96.svg")
 765                        .text_color(cx.theme().colors().text)
 766                        .w(px(40.))
 767                        .h(px(40.))
 768                        .mx_auto()
 769                        .mb_4(),
 770                ),
 771            )
 772            .map(|parent| {
 773                match configuration_error {
 774                    Some(ConfigurationError::ProviderNotAuthenticated) | Some(ConfigurationError::NoProvider)  => {
 775                        parent.child(
 776                            v_flex()
 777                                .gap_0p5()
 778                                .child(create_welcome_heading())
 779                                .child(
 780                                    h_flex().mb_2().w_full().justify_center().child(
 781                                        Label::new(
 782                                            "To start using the assistant, configure at least one LLM provider.",
 783                                        )
 784                                        .color(Color::Muted),
 785                                    ),
 786                                )
 787                                .child(
 788                                    h_flex().w_full().justify_center().child(
 789                                        Button::new("open-configuration", "Configure a Provider")
 790                                            .size(ButtonSize::Compact)
 791                                            .icon(Some(IconName::Sliders))
 792                                            .icon_size(IconSize::Small)
 793                                            .icon_position(IconPosition::Start)
 794                                            .on_click(cx.listener(|this, _, window, cx| {
 795                                                this.open_configuration(window, cx);
 796                                            })),
 797                                    ),
 798                                ),
 799                        )
 800                    }
 801                    Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
 802                        parent.child(
 803                            v_flex()
 804                                .gap_0p5()
 805                                .child(create_welcome_heading())
 806                                .children(provider.render_accept_terms(
 807                                    LanguageModelProviderTosView::ThreadEmptyState,
 808                                    cx,
 809                                )),
 810                        )
 811                    }
 812                    None => parent,
 813                }
 814            })
 815            .when(
 816                recent_threads.is_empty() && no_error,
 817                |parent| {
 818                    parent.child(
 819                        v_flex().gap_0p5().child(create_welcome_heading()).child(
 820                            h_flex().w_full().justify_center().child(
 821                                Label::new("Start typing to chat with your codebase")
 822                                    .color(Color::Muted),
 823                            ),
 824                        ),
 825                    )
 826                },
 827            )
 828            .when(!recent_threads.is_empty(), |parent| {
 829                parent
 830                    .child(
 831                        h_flex().w_full().justify_center().child(
 832                            Label::new("Recent Threads:")
 833                                .size(LabelSize::Small)
 834                                .color(Color::Muted),
 835                        ),
 836                    )
 837                    .child(v_flex().mx_auto().w_4_5().gap_2().children(
 838                        recent_threads.into_iter().map(|thread| {
 839                            // TODO: keyboard navigation
 840                            PastThread::new(thread, cx.entity().downgrade(), false)
 841                        }),
 842                    ))
 843                    .child(
 844                        h_flex().w_full().justify_center().child(
 845                            Button::new("view-all-past-threads", "View All Past Threads")
 846                                .style(ButtonStyle::Subtle)
 847                                .label_size(LabelSize::Small)
 848                                .key_binding(KeyBinding::for_action_in(
 849                                    &OpenHistory,
 850                                    &self.focus_handle(cx),
 851                                    window,
 852                                ))
 853                                .on_click(move |_event, window, cx| {
 854                                    window.dispatch_action(OpenHistory.boxed_clone(), cx);
 855                                }),
 856                        ),
 857                    )
 858            })
 859    }
 860
 861    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 862        let last_error = self.thread.read(cx).last_error()?;
 863
 864        Some(
 865            div()
 866                .absolute()
 867                .right_3()
 868                .bottom_12()
 869                .max_w_96()
 870                .py_2()
 871                .px_3()
 872                .elevation_2(cx)
 873                .occlude()
 874                .child(match last_error {
 875                    ThreadError::PaymentRequired => self.render_payment_required_error(cx),
 876                    ThreadError::MaxMonthlySpendReached => {
 877                        self.render_max_monthly_spend_reached_error(cx)
 878                    }
 879                    ThreadError::Message(error_message) => {
 880                        self.render_error_message(&error_message, cx)
 881                    }
 882                })
 883                .into_any(),
 884        )
 885    }
 886
 887    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
 888        const ERROR_MESSAGE: &str = "Free tier exceeded. Subscribe and add payment to continue using Zed LLMs. You'll be billed at cost for tokens used.";
 889
 890        v_flex()
 891            .gap_0p5()
 892            .child(
 893                h_flex()
 894                    .gap_1p5()
 895                    .items_center()
 896                    .child(Icon::new(IconName::XCircle).color(Color::Error))
 897                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
 898            )
 899            .child(
 900                div()
 901                    .id("error-message")
 902                    .max_h_24()
 903                    .overflow_y_scroll()
 904                    .child(Label::new(ERROR_MESSAGE)),
 905            )
 906            .child(
 907                h_flex()
 908                    .justify_end()
 909                    .mt_1()
 910                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
 911                        |this, _, _, cx| {
 912                            this.thread.update(cx, |this, _cx| {
 913                                this.clear_last_error();
 914                            });
 915
 916                            cx.open_url(&zed_urls::account_url(cx));
 917                            cx.notify();
 918                        },
 919                    )))
 920                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
 921                        |this, _, _, cx| {
 922                            this.thread.update(cx, |this, _cx| {
 923                                this.clear_last_error();
 924                            });
 925
 926                            cx.notify();
 927                        },
 928                    ))),
 929            )
 930            .into_any()
 931    }
 932
 933    fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
 934        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
 935
 936        v_flex()
 937            .gap_0p5()
 938            .child(
 939                h_flex()
 940                    .gap_1p5()
 941                    .items_center()
 942                    .child(Icon::new(IconName::XCircle).color(Color::Error))
 943                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
 944            )
 945            .child(
 946                div()
 947                    .id("error-message")
 948                    .max_h_24()
 949                    .overflow_y_scroll()
 950                    .child(Label::new(ERROR_MESSAGE)),
 951            )
 952            .child(
 953                h_flex()
 954                    .justify_end()
 955                    .mt_1()
 956                    .child(
 957                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
 958                            cx.listener(|this, _, _, cx| {
 959                                this.thread.update(cx, |this, _cx| {
 960                                    this.clear_last_error();
 961                                });
 962
 963                                cx.open_url(&zed_urls::account_url(cx));
 964                                cx.notify();
 965                            }),
 966                        ),
 967                    )
 968                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
 969                        |this, _, _, cx| {
 970                            this.thread.update(cx, |this, _cx| {
 971                                this.clear_last_error();
 972                            });
 973
 974                            cx.notify();
 975                        },
 976                    ))),
 977            )
 978            .into_any()
 979    }
 980
 981    fn render_error_message(
 982        &self,
 983        error_message: &SharedString,
 984        cx: &mut Context<Self>,
 985    ) -> AnyElement {
 986        v_flex()
 987            .gap_0p5()
 988            .child(
 989                h_flex()
 990                    .gap_1p5()
 991                    .items_center()
 992                    .child(Icon::new(IconName::XCircle).color(Color::Error))
 993                    .child(
 994                        Label::new("Error interacting with language model")
 995                            .weight(FontWeight::MEDIUM),
 996                    ),
 997            )
 998            .child(
 999                div()
1000                    .id("error-message")
1001                    .max_h_32()
1002                    .overflow_y_scroll()
1003                    .child(Label::new(error_message.clone())),
1004            )
1005            .child(
1006                h_flex()
1007                    .justify_end()
1008                    .mt_1()
1009                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1010                        |this, _, _, cx| {
1011                            this.thread.update(cx, |this, _cx| {
1012                                this.clear_last_error();
1013                            });
1014
1015                            cx.notify();
1016                        },
1017                    ))),
1018            )
1019            .into_any()
1020    }
1021}
1022
1023impl Render for AssistantPanel {
1024    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1025        v_flex()
1026            .key_context("AssistantPanel2")
1027            .justify_between()
1028            .size_full()
1029            .on_action(cx.listener(Self::cancel))
1030            .on_action(cx.listener(|this, _: &NewThread, window, cx| {
1031                this.new_thread(window, cx);
1032            }))
1033            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
1034                this.open_history(window, cx);
1035            }))
1036            .on_action(cx.listener(Self::deploy_prompt_library))
1037            .child(self.render_toolbar(cx))
1038            .map(|parent| match self.active_view {
1039                ActiveView::Thread => parent
1040                    .child(self.render_active_thread_or_empty_state(window, cx))
1041                    .child(
1042                        h_flex()
1043                            .border_t_1()
1044                            .border_color(cx.theme().colors().border)
1045                            .child(self.message_editor.clone()),
1046                    )
1047                    .children(self.render_last_error(cx)),
1048                ActiveView::History => parent.child(self.history.clone()),
1049                ActiveView::PromptEditor => parent.children(self.context_editor.clone()),
1050                ActiveView::PromptEditorHistory => parent.children(self.context_history.clone()),
1051                ActiveView::Configuration => parent.children(self.configuration.clone()),
1052            })
1053    }
1054}
1055
1056struct PromptLibraryInlineAssist {
1057    workspace: WeakEntity<Workspace>,
1058}
1059
1060impl PromptLibraryInlineAssist {
1061    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
1062        Self { workspace }
1063    }
1064}
1065
1066impl prompt_library::InlineAssistDelegate for PromptLibraryInlineAssist {
1067    fn assist(
1068        &self,
1069        prompt_editor: &Entity<Editor>,
1070        _initial_prompt: Option<String>,
1071        window: &mut Window,
1072        cx: &mut Context<PromptLibrary>,
1073    ) {
1074        InlineAssistant::update_global(cx, |assistant, cx| {
1075            assistant.assist(&prompt_editor, self.workspace.clone(), None, window, cx)
1076        })
1077    }
1078
1079    fn focus_assistant_panel(
1080        &self,
1081        workspace: &mut Workspace,
1082        window: &mut Window,
1083        cx: &mut Context<Workspace>,
1084    ) -> bool {
1085        workspace
1086            .focus_panel::<AssistantPanel>(window, cx)
1087            .is_some()
1088    }
1089}
1090
1091pub struct ConcreteAssistantPanelDelegate;
1092
1093impl AssistantPanelDelegate for ConcreteAssistantPanelDelegate {
1094    fn active_context_editor(
1095        &self,
1096        workspace: &mut Workspace,
1097        _window: &mut Window,
1098        cx: &mut Context<Workspace>,
1099    ) -> Option<Entity<ContextEditor>> {
1100        let panel = workspace.panel::<AssistantPanel>(cx)?;
1101        panel.update(cx, |panel, _cx| panel.context_editor.clone())
1102    }
1103
1104    fn open_saved_context(
1105        &self,
1106        workspace: &mut Workspace,
1107        path: std::path::PathBuf,
1108        window: &mut Window,
1109        cx: &mut Context<Workspace>,
1110    ) -> Task<Result<()>> {
1111        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1112            return Task::ready(Err(anyhow!("Assistant panel not found")));
1113        };
1114
1115        panel.update(cx, |panel, cx| {
1116            panel.open_saved_prompt_editor(path, window, cx)
1117        })
1118    }
1119
1120    fn open_remote_context(
1121        &self,
1122        _workspace: &mut Workspace,
1123        _context_id: assistant_context_editor::ContextId,
1124        _window: &mut Window,
1125        _cx: &mut Context<Workspace>,
1126    ) -> Task<Result<Entity<ContextEditor>>> {
1127        Task::ready(Err(anyhow!("opening remote context not implemented")))
1128    }
1129
1130    fn quote_selection(
1131        &self,
1132        _workspace: &mut Workspace,
1133        _creases: Vec<(String, String)>,
1134        _window: &mut Window,
1135        _cx: &mut Context<Workspace>,
1136    ) {
1137    }
1138}