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