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, render_remaining_tokens, AssistantPanelDelegate, ConfigurationError,
   7    ContextEditor, 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                    .w_full()
 639                    .gap_1()
 640                    .justify_between()
 641                    .child(
 642                        h_flex()
 643                            .child(Label::new(title))
 644                            .when(sub_title.is_some(), |this| {
 645                                this.child(
 646                                    h_flex()
 647                                        .pl_1p5()
 648                                        .gap_1p5()
 649                                        .child(
 650                                            Label::new("/")
 651                                                .size(LabelSize::Small)
 652                                                .color(Color::Disabled)
 653                                                .alpha(0.5),
 654                                        )
 655                                        .child(Label::new(sub_title.unwrap())),
 656                                )
 657                            }),
 658                    )
 659                    .children(if matches!(self.active_view, ActiveView::PromptEditor) {
 660                        self.context_editor
 661                            .as_ref()
 662                            .and_then(|editor| render_remaining_tokens(editor, cx))
 663                    } else {
 664                        None
 665                    }),
 666            )
 667            .child(
 668                h_flex()
 669                    .h_full()
 670                    .pl_1p5()
 671                    .border_l_1()
 672                    .border_color(cx.theme().colors().border)
 673                    .gap(DynamicSpacing::Base02.rems(cx))
 674                    .child(
 675                        PopoverMenu::new("assistant-toolbar-new-popover-menu")
 676                            .trigger_with_tooltip(
 677                                IconButton::new("new", IconName::Plus)
 678                                    .icon_size(IconSize::Small)
 679                                    .style(ButtonStyle::Subtle),
 680                                Tooltip::text("New…"),
 681                            )
 682                            .anchor(Corner::TopRight)
 683                            .with_handle(self.new_item_context_menu_handle.clone())
 684                            .menu(move |window, cx| {
 685                                Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 686                                    menu.action("New Thread", NewThread.boxed_clone())
 687                                        .action("New Prompt Editor", NewPromptEditor.boxed_clone())
 688                                }))
 689                            }),
 690                    )
 691                    .child(
 692                        PopoverMenu::new("assistant-toolbar-history-popover-menu")
 693                            .trigger_with_tooltip(
 694                                IconButton::new("open-history", IconName::HistoryRerun)
 695                                    .icon_size(IconSize::Small)
 696                                    .style(ButtonStyle::Subtle),
 697                                Tooltip::text("History…"),
 698                            )
 699                            .anchor(Corner::TopRight)
 700                            .with_handle(self.open_history_context_menu_handle.clone())
 701                            .menu(move |window, cx| {
 702                                Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 703                                    menu.action("Thread History", OpenHistory.boxed_clone())
 704                                        .action(
 705                                            "Prompt Editor History",
 706                                            OpenPromptEditorHistory.boxed_clone(),
 707                                        )
 708                                }))
 709                            }),
 710                    )
 711                    .child(
 712                        IconButton::new("configure-assistant", IconName::Settings)
 713                            .icon_size(IconSize::Small)
 714                            .style(ButtonStyle::Subtle)
 715                            .tooltip(Tooltip::text("Assistant Settings"))
 716                            .on_click(move |_event, window, cx| {
 717                                window.dispatch_action(OpenConfiguration.boxed_clone(), cx);
 718                            }),
 719                    ),
 720            )
 721    }
 722
 723    fn render_active_thread_or_empty_state(
 724        &self,
 725        window: &mut Window,
 726        cx: &mut Context<Self>,
 727    ) -> AnyElement {
 728        if self.thread.read(cx).is_empty() {
 729            return self
 730                .render_thread_empty_state(window, cx)
 731                .into_any_element();
 732        }
 733
 734        self.thread.clone().into_any_element()
 735    }
 736
 737    fn configuration_error(&self, cx: &App) -> Option<ConfigurationError> {
 738        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
 739            return Some(ConfigurationError::NoProvider);
 740        };
 741
 742        if !provider.is_authenticated(cx) {
 743            return Some(ConfigurationError::ProviderNotAuthenticated);
 744        }
 745
 746        if provider.must_accept_terms(cx) {
 747            return Some(ConfigurationError::ProviderPendingTermsAcceptance(provider));
 748        }
 749
 750        None
 751    }
 752
 753    fn render_thread_empty_state(
 754        &self,
 755        window: &mut Window,
 756        cx: &mut Context<Self>,
 757    ) -> impl IntoElement {
 758        let recent_threads = self
 759            .thread_store
 760            .update(cx, |this, _cx| this.recent_threads(3));
 761
 762        let create_welcome_heading = || {
 763            h_flex()
 764                .w_full()
 765                .justify_center()
 766                .child(Headline::new("Welcome to the Assistant Panel").size(HeadlineSize::Small))
 767        };
 768
 769        let configuration_error = self.configuration_error(cx);
 770        let no_error = configuration_error.is_none();
 771
 772        v_flex()
 773            .gap_2()
 774            .child(
 775                v_flex().w_full().child(
 776                    svg()
 777                        .path("icons/logo_96.svg")
 778                        .text_color(cx.theme().colors().text)
 779                        .w(px(40.))
 780                        .h(px(40.))
 781                        .mx_auto()
 782                        .mb_4(),
 783                ),
 784            )
 785            .map(|parent| {
 786                match configuration_error {
 787                    Some(ConfigurationError::ProviderNotAuthenticated) | Some(ConfigurationError::NoProvider)  => {
 788                        parent.child(
 789                            v_flex()
 790                                .gap_0p5()
 791                                .child(create_welcome_heading())
 792                                .child(
 793                                    h_flex().mb_2().w_full().justify_center().child(
 794                                        Label::new(
 795                                            "To start using the assistant, configure at least one LLM provider.",
 796                                        )
 797                                        .color(Color::Muted),
 798                                    ),
 799                                )
 800                                .child(
 801                                    h_flex().w_full().justify_center().child(
 802                                        Button::new("open-configuration", "Configure a Provider")
 803                                            .size(ButtonSize::Compact)
 804                                            .icon(Some(IconName::Sliders))
 805                                            .icon_size(IconSize::Small)
 806                                            .icon_position(IconPosition::Start)
 807                                            .on_click(cx.listener(|this, _, window, cx| {
 808                                                this.open_configuration(window, cx);
 809                                            })),
 810                                    ),
 811                                ),
 812                        )
 813                    }
 814                    Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
 815                        parent.child(
 816                            v_flex()
 817                                .gap_0p5()
 818                                .child(create_welcome_heading())
 819                                .children(provider.render_accept_terms(
 820                                    LanguageModelProviderTosView::ThreadEmptyState,
 821                                    cx,
 822                                )),
 823                        )
 824                    }
 825                    None => parent,
 826                }
 827            })
 828            .when(
 829                recent_threads.is_empty() && no_error,
 830                |parent| {
 831                    parent.child(
 832                        v_flex().gap_0p5().child(create_welcome_heading()).child(
 833                            h_flex().w_full().justify_center().child(
 834                                Label::new("Start typing to chat with your codebase")
 835                                    .color(Color::Muted),
 836                            ),
 837                        ),
 838                    )
 839                },
 840            )
 841            .when(!recent_threads.is_empty(), |parent| {
 842                parent
 843                    .child(
 844                        h_flex().w_full().justify_center().child(
 845                            Label::new("Recent Threads:")
 846                                .size(LabelSize::Small)
 847                                .color(Color::Muted),
 848                        ),
 849                    )
 850                    .child(v_flex().mx_auto().w_4_5().gap_2().children(
 851                        recent_threads.into_iter().map(|thread| {
 852                            // TODO: keyboard navigation
 853                            PastThread::new(thread, cx.entity().downgrade(), false)
 854                        }),
 855                    ))
 856                    .child(
 857                        h_flex().w_full().justify_center().child(
 858                            Button::new("view-all-past-threads", "View All Past Threads")
 859                                .style(ButtonStyle::Subtle)
 860                                .label_size(LabelSize::Small)
 861                                .key_binding(KeyBinding::for_action_in(
 862                                    &OpenHistory,
 863                                    &self.focus_handle(cx),
 864                                    window,
 865                                    cx
 866                                ))
 867                                .on_click(move |_event, window, cx| {
 868                                    window.dispatch_action(OpenHistory.boxed_clone(), cx);
 869                                }),
 870                        ),
 871                    )
 872            })
 873    }
 874
 875    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 876        let last_error = self.thread.read(cx).last_error()?;
 877
 878        Some(
 879            div()
 880                .absolute()
 881                .right_3()
 882                .bottom_12()
 883                .max_w_96()
 884                .py_2()
 885                .px_3()
 886                .elevation_2(cx)
 887                .occlude()
 888                .child(match last_error {
 889                    ThreadError::PaymentRequired => self.render_payment_required_error(cx),
 890                    ThreadError::MaxMonthlySpendReached => {
 891                        self.render_max_monthly_spend_reached_error(cx)
 892                    }
 893                    ThreadError::Message(error_message) => {
 894                        self.render_error_message(&error_message, cx)
 895                    }
 896                })
 897                .into_any(),
 898        )
 899    }
 900
 901    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
 902        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.";
 903
 904        v_flex()
 905            .gap_0p5()
 906            .child(
 907                h_flex()
 908                    .gap_1p5()
 909                    .items_center()
 910                    .child(Icon::new(IconName::XCircle).color(Color::Error))
 911                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
 912            )
 913            .child(
 914                div()
 915                    .id("error-message")
 916                    .max_h_24()
 917                    .overflow_y_scroll()
 918                    .child(Label::new(ERROR_MESSAGE)),
 919            )
 920            .child(
 921                h_flex()
 922                    .justify_end()
 923                    .mt_1()
 924                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
 925                        |this, _, _, cx| {
 926                            this.thread.update(cx, |this, _cx| {
 927                                this.clear_last_error();
 928                            });
 929
 930                            cx.open_url(&zed_urls::account_url(cx));
 931                            cx.notify();
 932                        },
 933                    )))
 934                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
 935                        |this, _, _, cx| {
 936                            this.thread.update(cx, |this, _cx| {
 937                                this.clear_last_error();
 938                            });
 939
 940                            cx.notify();
 941                        },
 942                    ))),
 943            )
 944            .into_any()
 945    }
 946
 947    fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
 948        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
 949
 950        v_flex()
 951            .gap_0p5()
 952            .child(
 953                h_flex()
 954                    .gap_1p5()
 955                    .items_center()
 956                    .child(Icon::new(IconName::XCircle).color(Color::Error))
 957                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
 958            )
 959            .child(
 960                div()
 961                    .id("error-message")
 962                    .max_h_24()
 963                    .overflow_y_scroll()
 964                    .child(Label::new(ERROR_MESSAGE)),
 965            )
 966            .child(
 967                h_flex()
 968                    .justify_end()
 969                    .mt_1()
 970                    .child(
 971                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
 972                            cx.listener(|this, _, _, cx| {
 973                                this.thread.update(cx, |this, _cx| {
 974                                    this.clear_last_error();
 975                                });
 976
 977                                cx.open_url(&zed_urls::account_url(cx));
 978                                cx.notify();
 979                            }),
 980                        ),
 981                    )
 982                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
 983                        |this, _, _, cx| {
 984                            this.thread.update(cx, |this, _cx| {
 985                                this.clear_last_error();
 986                            });
 987
 988                            cx.notify();
 989                        },
 990                    ))),
 991            )
 992            .into_any()
 993    }
 994
 995    fn render_error_message(
 996        &self,
 997        error_message: &SharedString,
 998        cx: &mut Context<Self>,
 999    ) -> AnyElement {
1000        v_flex()
1001            .gap_0p5()
1002            .child(
1003                h_flex()
1004                    .gap_1p5()
1005                    .items_center()
1006                    .child(Icon::new(IconName::XCircle).color(Color::Error))
1007                    .child(
1008                        Label::new("Error interacting with language model")
1009                            .weight(FontWeight::MEDIUM),
1010                    ),
1011            )
1012            .child(
1013                div()
1014                    .id("error-message")
1015                    .max_h_32()
1016                    .overflow_y_scroll()
1017                    .child(Label::new(error_message.clone())),
1018            )
1019            .child(
1020                h_flex()
1021                    .justify_end()
1022                    .mt_1()
1023                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1024                        |this, _, _, cx| {
1025                            this.thread.update(cx, |this, _cx| {
1026                                this.clear_last_error();
1027                            });
1028
1029                            cx.notify();
1030                        },
1031                    ))),
1032            )
1033            .into_any()
1034    }
1035}
1036
1037impl Render for AssistantPanel {
1038    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1039        v_flex()
1040            .key_context("AssistantPanel2")
1041            .justify_between()
1042            .size_full()
1043            .on_action(cx.listener(Self::cancel))
1044            .on_action(cx.listener(|this, _: &NewThread, window, cx| {
1045                this.new_thread(window, cx);
1046            }))
1047            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
1048                this.open_history(window, cx);
1049            }))
1050            .on_action(cx.listener(Self::deploy_prompt_library))
1051            .child(self.render_toolbar(cx))
1052            .map(|parent| match self.active_view {
1053                ActiveView::Thread => parent
1054                    .child(self.render_active_thread_or_empty_state(window, cx))
1055                    .child(
1056                        h_flex()
1057                            .border_t_1()
1058                            .border_color(cx.theme().colors().border)
1059                            .child(self.message_editor.clone()),
1060                    )
1061                    .children(self.render_last_error(cx)),
1062                ActiveView::History => parent.child(self.history.clone()),
1063                ActiveView::PromptEditor => parent.children(self.context_editor.clone()),
1064                ActiveView::PromptEditorHistory => parent.children(self.context_history.clone()),
1065                ActiveView::Configuration => parent.children(self.configuration.clone()),
1066            })
1067    }
1068}
1069
1070struct PromptLibraryInlineAssist {
1071    workspace: WeakEntity<Workspace>,
1072}
1073
1074impl PromptLibraryInlineAssist {
1075    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
1076        Self { workspace }
1077    }
1078}
1079
1080impl prompt_library::InlineAssistDelegate for PromptLibraryInlineAssist {
1081    fn assist(
1082        &self,
1083        prompt_editor: &Entity<Editor>,
1084        _initial_prompt: Option<String>,
1085        window: &mut Window,
1086        cx: &mut Context<PromptLibrary>,
1087    ) {
1088        InlineAssistant::update_global(cx, |assistant, cx| {
1089            assistant.assist(&prompt_editor, self.workspace.clone(), None, window, cx)
1090        })
1091    }
1092
1093    fn focus_assistant_panel(
1094        &self,
1095        workspace: &mut Workspace,
1096        window: &mut Window,
1097        cx: &mut Context<Workspace>,
1098    ) -> bool {
1099        workspace
1100            .focus_panel::<AssistantPanel>(window, cx)
1101            .is_some()
1102    }
1103}
1104
1105pub struct ConcreteAssistantPanelDelegate;
1106
1107impl AssistantPanelDelegate for ConcreteAssistantPanelDelegate {
1108    fn active_context_editor(
1109        &self,
1110        workspace: &mut Workspace,
1111        _window: &mut Window,
1112        cx: &mut Context<Workspace>,
1113    ) -> Option<Entity<ContextEditor>> {
1114        let panel = workspace.panel::<AssistantPanel>(cx)?;
1115        panel.update(cx, |panel, _cx| panel.context_editor.clone())
1116    }
1117
1118    fn open_saved_context(
1119        &self,
1120        workspace: &mut Workspace,
1121        path: std::path::PathBuf,
1122        window: &mut Window,
1123        cx: &mut Context<Workspace>,
1124    ) -> Task<Result<()>> {
1125        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1126            return Task::ready(Err(anyhow!("Assistant panel not found")));
1127        };
1128
1129        panel.update(cx, |panel, cx| {
1130            panel.open_saved_prompt_editor(path, window, cx)
1131        })
1132    }
1133
1134    fn open_remote_context(
1135        &self,
1136        _workspace: &mut Workspace,
1137        _context_id: assistant_context_editor::ContextId,
1138        _window: &mut Window,
1139        _cx: &mut Context<Workspace>,
1140    ) -> Task<Result<Entity<ContextEditor>>> {
1141        Task::ready(Err(anyhow!("opening remote context not implemented")))
1142    }
1143
1144    fn quote_selection(
1145        &self,
1146        _workspace: &mut Workspace,
1147        _creases: Vec<(String, String)>,
1148        _window: &mut Window,
1149        _cx: &mut Context<Workspace>,
1150    ) {
1151    }
1152}