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