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