1use std::ops::Range;
2use std::path::PathBuf;
3use std::sync::Arc;
4use std::time::Duration;
5
6use anyhow::{Result, anyhow};
7use assistant_context_editor::{
8 AssistantPanelDelegate, ConfigurationError, ContextEditor, SlashCommandCompletionProvider,
9 humanize_token_count, make_lsp_adapter_delegate, render_remaining_tokens,
10};
11use assistant_settings::{AssistantDockPosition, AssistantSettings};
12use assistant_slash_command::SlashCommandWorkingSet;
13use assistant_tool::ToolWorkingSet;
14
15use client::zed_urls;
16use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
17use fs::Fs;
18use gpui::{
19 Action, Animation, AnimationExt as _, AnyElement, App, AsyncWindowContext, Corner, Entity,
20 EventEmitter, FocusHandle, Focusable, FontWeight, KeyContext, Pixels, Subscription, Task,
21 UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
22};
23use language::LanguageRegistry;
24use language_model::{LanguageModelProviderTosView, LanguageModelRegistry};
25use language_model_selector::ToggleModelSelector;
26use project::Project;
27use prompt_library::{PromptLibrary, open_prompt_library};
28use prompt_store::{PromptBuilder, PromptId};
29use proto::Plan;
30use settings::{Settings, update_settings_file};
31use time::UtcOffset;
32use ui::{
33 Banner, ContextMenu, KeyBinding, PopoverMenu, PopoverMenuHandle, Tab, Tooltip, prelude::*,
34};
35use util::ResultExt as _;
36use workspace::Workspace;
37use workspace::dock::{DockPosition, Panel, PanelEvent};
38use zed_actions::agent::OpenConfiguration;
39use zed_actions::assistant::{OpenPromptLibrary, ToggleFocus};
40
41use crate::active_thread::{ActiveThread, ActiveThreadEvent};
42use crate::assistant_configuration::{AssistantConfiguration, AssistantConfigurationEvent};
43use crate::history_store::{HistoryEntry, HistoryStore};
44use crate::message_editor::{MessageEditor, MessageEditorEvent};
45use crate::thread::{Thread, ThreadError, ThreadId, TokenUsageRatio};
46use crate::thread_history::{PastContext, PastThread, ThreadHistory};
47use crate::thread_store::ThreadStore;
48use crate::ui::UsageBanner;
49use crate::{
50 AgentDiff, ExpandMessageEditor, InlineAssistant, NewTextThread, NewThread,
51 OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ThreadEvent, ToggleContextPicker,
52};
53
54pub fn init(cx: &mut App) {
55 cx.observe_new(
56 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
57 workspace
58 .register_action(|workspace, action: &NewThread, window, cx| {
59 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
60 panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
61 workspace.focus_panel::<AssistantPanel>(window, cx);
62 }
63 })
64 .register_action(|workspace, _: &OpenHistory, window, cx| {
65 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
66 workspace.focus_panel::<AssistantPanel>(window, cx);
67 panel.update(cx, |panel, cx| panel.open_history(window, cx));
68 }
69 })
70 .register_action(|workspace, _: &OpenConfiguration, window, cx| {
71 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
72 workspace.focus_panel::<AssistantPanel>(window, cx);
73 panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
74 }
75 })
76 .register_action(|workspace, _: &NewTextThread, window, cx| {
77 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
78 workspace.focus_panel::<AssistantPanel>(window, cx);
79 panel.update(cx, |panel, cx| panel.new_prompt_editor(window, cx));
80 }
81 })
82 .register_action(|workspace, _: &OpenPromptLibrary, window, cx| {
83 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
84 workspace.focus_panel::<AssistantPanel>(window, cx);
85 panel.update(cx, |panel, cx| {
86 panel.deploy_prompt_library(&OpenPromptLibrary::default(), window, cx)
87 });
88 }
89 })
90 .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
91 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
92 workspace.focus_panel::<AssistantPanel>(window, cx);
93 let thread = panel.read(cx).thread.read(cx).thread().clone();
94 AgentDiff::deploy_in_workspace(thread, workspace, window, cx);
95 }
96 })
97 .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
98 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
99 workspace.focus_panel::<AssistantPanel>(window, cx);
100 panel.update(cx, |panel, cx| {
101 panel.message_editor.update(cx, |editor, cx| {
102 editor.expand_message_editor(&ExpandMessageEditor, window, cx);
103 });
104 });
105 }
106 });
107 },
108 )
109 .detach();
110}
111
112enum ActiveView {
113 Thread {
114 change_title_editor: Entity<Editor>,
115 _subscriptions: Vec<gpui::Subscription>,
116 },
117 PromptEditor {
118 context_editor: Entity<ContextEditor>,
119 },
120 History,
121 Configuration,
122}
123
124impl ActiveView {
125 pub fn thread(thread: Entity<Thread>, window: &mut Window, cx: &mut App) -> Self {
126 let summary = thread.read(cx).summary_or_default();
127
128 let editor = cx.new(|cx| {
129 let mut editor = Editor::single_line(window, cx);
130 editor.set_text(summary, window, cx);
131 editor
132 });
133
134 let subscriptions = vec![
135 window.subscribe(&editor, cx, {
136 {
137 let thread = thread.clone();
138 move |editor, event, window, cx| match event {
139 EditorEvent::BufferEdited => {
140 let new_summary = editor.read(cx).text(cx);
141
142 thread.update(cx, |thread, cx| {
143 thread.set_summary(new_summary, cx);
144 })
145 }
146 EditorEvent::Blurred => {
147 if editor.read(cx).text(cx).is_empty() {
148 let summary = thread.read(cx).summary_or_default();
149
150 editor.update(cx, |editor, cx| {
151 editor.set_text(summary, window, cx);
152 });
153 }
154 }
155 _ => {}
156 }
157 }
158 }),
159 window.subscribe(&thread, cx, {
160 let editor = editor.clone();
161 move |thread, event, window, cx| match event {
162 ThreadEvent::SummaryGenerated => {
163 let summary = thread.read(cx).summary_or_default();
164
165 editor.update(cx, |editor, cx| {
166 editor.set_text(summary, window, cx);
167 })
168 }
169 _ => {}
170 }
171 }),
172 ];
173
174 Self::Thread {
175 change_title_editor: editor,
176 _subscriptions: subscriptions,
177 }
178 }
179}
180
181pub struct AssistantPanel {
182 workspace: WeakEntity<Workspace>,
183 project: Entity<Project>,
184 fs: Arc<dyn Fs>,
185 language_registry: Arc<LanguageRegistry>,
186 thread_store: Entity<ThreadStore>,
187 thread: Entity<ActiveThread>,
188 message_editor: Entity<MessageEditor>,
189 _active_thread_subscriptions: Vec<Subscription>,
190 context_store: Entity<assistant_context_editor::ContextStore>,
191 configuration: Option<Entity<AssistantConfiguration>>,
192 configuration_subscription: Option<Subscription>,
193 local_timezone: UtcOffset,
194 active_view: ActiveView,
195 previous_view: Option<ActiveView>,
196 history_store: Entity<HistoryStore>,
197 history: Entity<ThreadHistory>,
198 assistant_dropdown_menu_handle: PopoverMenuHandle<ContextMenu>,
199 width: Option<Pixels>,
200 height: Option<Pixels>,
201}
202
203impl AssistantPanel {
204 pub fn load(
205 workspace: WeakEntity<Workspace>,
206 prompt_builder: Arc<PromptBuilder>,
207 cx: AsyncWindowContext,
208 ) -> Task<Result<Entity<Self>>> {
209 cx.spawn(async move |cx| {
210 let tools = cx.new(|_| ToolWorkingSet::default())?;
211 let thread_store = workspace
212 .update(cx, |workspace, cx| {
213 let project = workspace.project().clone();
214 ThreadStore::load(project, tools.clone(), prompt_builder.clone(), cx)
215 })?
216 .await?;
217
218 let slash_commands = Arc::new(SlashCommandWorkingSet::default());
219 let context_store = workspace
220 .update(cx, |workspace, cx| {
221 let project = workspace.project().clone();
222 assistant_context_editor::ContextStore::new(
223 project,
224 prompt_builder.clone(),
225 slash_commands,
226 cx,
227 )
228 })?
229 .await?;
230
231 workspace.update_in(cx, |workspace, window, cx| {
232 cx.new(|cx| Self::new(workspace, thread_store, context_store, window, cx))
233 })
234 })
235 }
236
237 fn new(
238 workspace: &Workspace,
239 thread_store: Entity<ThreadStore>,
240 context_store: Entity<assistant_context_editor::ContextStore>,
241 window: &mut Window,
242 cx: &mut Context<Self>,
243 ) -> Self {
244 let thread = thread_store.update(cx, |this, cx| this.create_thread(cx));
245 let fs = workspace.app_state().fs.clone();
246 let project = workspace.project();
247 let language_registry = project.read(cx).languages().clone();
248 let workspace = workspace.weak_handle();
249 let weak_self = cx.entity().downgrade();
250
251 let message_editor_context_store = cx.new(|_cx| {
252 crate::context_store::ContextStore::new(
253 project.downgrade(),
254 Some(thread_store.downgrade()),
255 )
256 });
257
258 let message_editor = cx.new(|cx| {
259 MessageEditor::new(
260 fs.clone(),
261 workspace.clone(),
262 message_editor_context_store.clone(),
263 thread_store.downgrade(),
264 thread.clone(),
265 window,
266 cx,
267 )
268 });
269
270 let message_editor_subscription =
271 cx.subscribe(&message_editor, |_, _, event, cx| match event {
272 MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
273 cx.notify();
274 }
275 });
276
277 let history_store =
278 cx.new(|cx| HistoryStore::new(thread_store.clone(), context_store.clone(), cx));
279
280 cx.observe(&history_store, |_, _, cx| cx.notify()).detach();
281
282 let active_view = ActiveView::thread(thread.clone(), window, cx);
283 let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
284 if let ThreadEvent::MessageAdded(_) = &event {
285 // needed to leave empty state
286 cx.notify();
287 }
288 });
289 let thread = cx.new(|cx| {
290 ActiveThread::new(
291 thread.clone(),
292 thread_store.clone(),
293 language_registry.clone(),
294 message_editor_context_store.clone(),
295 workspace.clone(),
296 window,
297 cx,
298 )
299 });
300
301 let active_thread_subscription = cx.subscribe(&thread, |_, _, event, cx| match &event {
302 ActiveThreadEvent::EditingMessageTokenCountChanged => {
303 cx.notify();
304 }
305 });
306
307 Self {
308 active_view,
309 workspace,
310 project: project.clone(),
311 fs: fs.clone(),
312 language_registry,
313 thread_store: thread_store.clone(),
314 thread,
315 message_editor,
316 _active_thread_subscriptions: vec![
317 thread_subscription,
318 active_thread_subscription,
319 message_editor_subscription,
320 ],
321 context_store,
322 configuration: None,
323 configuration_subscription: None,
324 local_timezone: UtcOffset::from_whole_seconds(
325 chrono::Local::now().offset().local_minus_utc(),
326 )
327 .unwrap(),
328 previous_view: None,
329 history_store: history_store.clone(),
330 history: cx.new(|cx| ThreadHistory::new(weak_self, history_store, window, cx)),
331 assistant_dropdown_menu_handle: PopoverMenuHandle::default(),
332 width: None,
333 height: None,
334 }
335 }
336
337 pub fn toggle_focus(
338 workspace: &mut Workspace,
339 _: &ToggleFocus,
340 window: &mut Window,
341 cx: &mut Context<Workspace>,
342 ) {
343 if workspace
344 .panel::<Self>(cx)
345 .is_some_and(|panel| panel.read(cx).enabled(cx))
346 {
347 workspace.toggle_panel_focus::<Self>(window, cx);
348 }
349 }
350
351 pub(crate) fn local_timezone(&self) -> UtcOffset {
352 self.local_timezone
353 }
354
355 pub(crate) fn thread_store(&self) -> &Entity<ThreadStore> {
356 &self.thread_store
357 }
358
359 fn cancel(
360 &mut self,
361 _: &editor::actions::Cancel,
362 _window: &mut Window,
363 cx: &mut Context<Self>,
364 ) {
365 self.thread
366 .update(cx, |thread, cx| thread.cancel_last_completion(cx));
367 }
368
369 fn new_thread(&mut self, action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
370 let thread = self
371 .thread_store
372 .update(cx, |this, cx| this.create_thread(cx));
373
374 let thread_view = ActiveView::thread(thread.clone(), window, cx);
375 self.set_active_view(thread_view, window, cx);
376
377 let message_editor_context_store = cx.new(|_cx| {
378 crate::context_store::ContextStore::new(
379 self.project.downgrade(),
380 Some(self.thread_store.downgrade()),
381 )
382 });
383
384 if let Some(other_thread_id) = action.from_thread_id.clone() {
385 let other_thread_task = self
386 .thread_store
387 .update(cx, |this, cx| this.open_thread(&other_thread_id, cx));
388
389 cx.spawn({
390 let context_store = message_editor_context_store.clone();
391
392 async move |_panel, cx| {
393 let other_thread = other_thread_task.await?;
394
395 context_store.update(cx, |this, cx| {
396 this.add_thread(other_thread, false, cx);
397 })?;
398 anyhow::Ok(())
399 }
400 })
401 .detach_and_log_err(cx);
402 }
403
404 let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
405 if let ThreadEvent::MessageAdded(_) = &event {
406 // needed to leave empty state
407 cx.notify();
408 }
409 });
410
411 self.thread = cx.new(|cx| {
412 ActiveThread::new(
413 thread.clone(),
414 self.thread_store.clone(),
415 self.language_registry.clone(),
416 message_editor_context_store.clone(),
417 self.workspace.clone(),
418 window,
419 cx,
420 )
421 });
422
423 let active_thread_subscription =
424 cx.subscribe(&self.thread, |_, _, event, cx| match &event {
425 ActiveThreadEvent::EditingMessageTokenCountChanged => {
426 cx.notify();
427 }
428 });
429
430 self.message_editor = cx.new(|cx| {
431 MessageEditor::new(
432 self.fs.clone(),
433 self.workspace.clone(),
434 message_editor_context_store,
435 self.thread_store.downgrade(),
436 thread,
437 window,
438 cx,
439 )
440 });
441 self.message_editor.focus_handle(cx).focus(window);
442
443 let message_editor_subscription =
444 cx.subscribe(&self.message_editor, |_, _, event, cx| match event {
445 MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
446 cx.notify();
447 }
448 });
449
450 self._active_thread_subscriptions = vec![
451 thread_subscription,
452 active_thread_subscription,
453 message_editor_subscription,
454 ];
455 }
456
457 fn new_prompt_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
458 let context = self
459 .context_store
460 .update(cx, |context_store, cx| context_store.create(cx));
461 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
462 .log_err()
463 .flatten();
464
465 let context_editor = cx.new(|cx| {
466 let mut editor = ContextEditor::for_context(
467 context,
468 self.fs.clone(),
469 self.workspace.clone(),
470 self.project.clone(),
471 lsp_adapter_delegate,
472 window,
473 cx,
474 );
475 editor.insert_default_prompt(window, cx);
476 editor
477 });
478
479 self.set_active_view(
480 ActiveView::PromptEditor {
481 context_editor: context_editor.clone(),
482 },
483 window,
484 cx,
485 );
486 context_editor.focus_handle(cx).focus(window);
487 }
488
489 fn deploy_prompt_library(
490 &mut self,
491 action: &OpenPromptLibrary,
492 _window: &mut Window,
493 cx: &mut Context<Self>,
494 ) {
495 open_prompt_library(
496 self.language_registry.clone(),
497 Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
498 Arc::new(|| {
499 Box::new(SlashCommandCompletionProvider::new(
500 Arc::new(SlashCommandWorkingSet::default()),
501 None,
502 None,
503 ))
504 }),
505 action.prompt_to_focus.map(|uuid| PromptId::User { uuid }),
506 cx,
507 )
508 .detach_and_log_err(cx);
509 }
510
511 fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
512 if matches!(self.active_view, ActiveView::History) {
513 if let Some(previous_view) = self.previous_view.take() {
514 self.set_active_view(previous_view, window, cx);
515 }
516 } else {
517 self.thread_store
518 .update(cx, |thread_store, cx| thread_store.reload(cx))
519 .detach_and_log_err(cx);
520 self.set_active_view(ActiveView::History, window, cx);
521 }
522 cx.notify();
523 }
524
525 pub(crate) fn open_saved_prompt_editor(
526 &mut self,
527 path: PathBuf,
528 window: &mut Window,
529 cx: &mut Context<Self>,
530 ) -> Task<Result<()>> {
531 let context = self
532 .context_store
533 .update(cx, |store, cx| store.open_local_context(path.clone(), cx));
534 let fs = self.fs.clone();
535 let project = self.project.clone();
536 let workspace = self.workspace.clone();
537
538 let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err().flatten();
539
540 cx.spawn_in(window, async move |this, cx| {
541 let context = context.await?;
542 this.update_in(cx, |this, window, cx| {
543 let editor = cx.new(|cx| {
544 ContextEditor::for_context(
545 context,
546 fs,
547 workspace,
548 project,
549 lsp_adapter_delegate,
550 window,
551 cx,
552 )
553 });
554 this.set_active_view(
555 ActiveView::PromptEditor {
556 context_editor: editor,
557 },
558 window,
559 cx,
560 );
561
562 anyhow::Ok(())
563 })??;
564 Ok(())
565 })
566 }
567
568 pub(crate) fn open_thread(
569 &mut self,
570 thread_id: &ThreadId,
571 window: &mut Window,
572 cx: &mut Context<Self>,
573 ) -> Task<Result<()>> {
574 let open_thread_task = self
575 .thread_store
576 .update(cx, |this, cx| this.open_thread(thread_id, cx));
577
578 cx.spawn_in(window, async move |this, cx| {
579 let thread = open_thread_task.await?;
580 this.update_in(cx, |this, window, cx| {
581 let thread_view = ActiveView::thread(thread.clone(), window, cx);
582 this.set_active_view(thread_view, window, cx);
583 let message_editor_context_store = cx.new(|_cx| {
584 crate::context_store::ContextStore::new(
585 this.project.downgrade(),
586 Some(this.thread_store.downgrade()),
587 )
588 });
589 let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
590 if let ThreadEvent::MessageAdded(_) = &event {
591 // needed to leave empty state
592 cx.notify();
593 }
594 });
595
596 this.thread = cx.new(|cx| {
597 ActiveThread::new(
598 thread.clone(),
599 this.thread_store.clone(),
600 this.language_registry.clone(),
601 message_editor_context_store.clone(),
602 this.workspace.clone(),
603 window,
604 cx,
605 )
606 });
607
608 let active_thread_subscription =
609 cx.subscribe(&this.thread, |_, _, event, cx| match &event {
610 ActiveThreadEvent::EditingMessageTokenCountChanged => {
611 cx.notify();
612 }
613 });
614
615 this.message_editor = cx.new(|cx| {
616 MessageEditor::new(
617 this.fs.clone(),
618 this.workspace.clone(),
619 message_editor_context_store,
620 this.thread_store.downgrade(),
621 thread,
622 window,
623 cx,
624 )
625 });
626 this.message_editor.focus_handle(cx).focus(window);
627
628 let message_editor_subscription =
629 cx.subscribe(&this.message_editor, |_, _, event, cx| match event {
630 MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
631 cx.notify();
632 }
633 });
634
635 this._active_thread_subscriptions = vec![
636 thread_subscription,
637 active_thread_subscription,
638 message_editor_subscription,
639 ];
640 })
641 })
642 }
643
644 pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
645 match self.active_view {
646 ActiveView::Configuration | ActiveView::History => {
647 self.active_view =
648 ActiveView::thread(self.thread.read(cx).thread().clone(), window, cx);
649 self.message_editor.focus_handle(cx).focus(window);
650 cx.notify();
651 }
652 _ => {}
653 }
654 }
655
656 pub fn open_agent_diff(
657 &mut self,
658 _: &OpenAgentDiff,
659 window: &mut Window,
660 cx: &mut Context<Self>,
661 ) {
662 let thread = self.thread.read(cx).thread().clone();
663 self.workspace
664 .update(cx, |workspace, cx| {
665 AgentDiff::deploy_in_workspace(thread, workspace, window, cx)
666 })
667 .log_err();
668 }
669
670 pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
671 let context_server_manager = self.thread_store.read(cx).context_server_manager();
672 let tools = self.thread_store.read(cx).tools();
673 let fs = self.fs.clone();
674
675 self.set_active_view(ActiveView::Configuration, window, cx);
676 self.configuration =
677 Some(cx.new(|cx| {
678 AssistantConfiguration::new(fs, context_server_manager, tools, window, cx)
679 }));
680
681 if let Some(configuration) = self.configuration.as_ref() {
682 self.configuration_subscription = Some(cx.subscribe_in(
683 configuration,
684 window,
685 Self::handle_assistant_configuration_event,
686 ));
687
688 configuration.focus_handle(cx).focus(window);
689 }
690 }
691
692 pub(crate) fn open_active_thread_as_markdown(
693 &mut self,
694 _: &OpenActiveThreadAsMarkdown,
695 window: &mut Window,
696 cx: &mut Context<Self>,
697 ) {
698 let Some(workspace) = self
699 .workspace
700 .upgrade()
701 .ok_or_else(|| anyhow!("workspace dropped"))
702 .log_err()
703 else {
704 return;
705 };
706
707 let markdown_language_task = workspace
708 .read(cx)
709 .app_state()
710 .languages
711 .language_for_name("Markdown");
712 let thread = self.active_thread(cx);
713 cx.spawn_in(window, async move |_this, cx| {
714 let markdown_language = markdown_language_task.await?;
715
716 workspace.update_in(cx, |workspace, window, cx| {
717 let thread = thread.read(cx);
718 let markdown = thread.to_markdown(cx)?;
719 let thread_summary = thread
720 .summary()
721 .map(|summary| summary.to_string())
722 .unwrap_or_else(|| "Thread".to_string());
723
724 let project = workspace.project().clone();
725 let buffer = project.update(cx, |project, cx| {
726 project.create_local_buffer(&markdown, Some(markdown_language), cx)
727 });
728 let buffer = cx.new(|cx| {
729 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
730 });
731
732 workspace.add_item_to_active_pane(
733 Box::new(cx.new(|cx| {
734 let mut editor =
735 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
736 editor.set_breadcrumb_header(thread_summary);
737 editor
738 })),
739 None,
740 true,
741 window,
742 cx,
743 );
744
745 anyhow::Ok(())
746 })
747 })
748 .detach_and_log_err(cx);
749 }
750
751 fn handle_assistant_configuration_event(
752 &mut self,
753 _entity: &Entity<AssistantConfiguration>,
754 event: &AssistantConfigurationEvent,
755 window: &mut Window,
756 cx: &mut Context<Self>,
757 ) {
758 match event {
759 AssistantConfigurationEvent::NewThread(provider) => {
760 if LanguageModelRegistry::read_global(cx)
761 .default_model()
762 .map_or(true, |model| model.provider.id() != provider.id())
763 {
764 if let Some(model) = provider.default_model(cx) {
765 update_settings_file::<AssistantSettings>(
766 self.fs.clone(),
767 cx,
768 move |settings, _| settings.set_model(model),
769 );
770 }
771 }
772
773 self.new_thread(&NewThread::default(), window, cx);
774 }
775 }
776 }
777
778 pub(crate) fn active_thread(&self, cx: &App) -> Entity<Thread> {
779 self.thread.read(cx).thread().clone()
780 }
781
782 pub(crate) fn delete_thread(
783 &mut self,
784 thread_id: &ThreadId,
785 cx: &mut Context<Self>,
786 ) -> Task<Result<()>> {
787 self.thread_store
788 .update(cx, |this, cx| this.delete_thread(thread_id, cx))
789 }
790
791 pub(crate) fn has_active_thread(&self) -> bool {
792 matches!(self.active_view, ActiveView::Thread { .. })
793 }
794
795 pub(crate) fn active_context_editor(&self) -> Option<Entity<ContextEditor>> {
796 match &self.active_view {
797 ActiveView::PromptEditor { context_editor } => Some(context_editor.clone()),
798 _ => None,
799 }
800 }
801
802 pub(crate) fn delete_context(
803 &mut self,
804 path: PathBuf,
805 cx: &mut Context<Self>,
806 ) -> Task<Result<()>> {
807 self.context_store
808 .update(cx, |this, cx| this.delete_local_context(path, cx))
809 }
810
811 fn set_active_view(
812 &mut self,
813 new_view: ActiveView,
814 window: &mut Window,
815 cx: &mut Context<Self>,
816 ) {
817 let current_is_history = matches!(self.active_view, ActiveView::History);
818 let new_is_history = matches!(new_view, ActiveView::History);
819
820 if current_is_history && !new_is_history {
821 self.active_view = new_view;
822 } else if !current_is_history && new_is_history {
823 self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
824 } else {
825 if !new_is_history {
826 self.previous_view = None;
827 }
828 self.active_view = new_view;
829 }
830
831 self.focus_handle(cx).focus(window);
832 }
833}
834
835impl Focusable for AssistantPanel {
836 fn focus_handle(&self, cx: &App) -> FocusHandle {
837 match &self.active_view {
838 ActiveView::Thread { .. } => self.message_editor.focus_handle(cx),
839 ActiveView::History => self.history.focus_handle(cx),
840 ActiveView::PromptEditor { context_editor } => context_editor.focus_handle(cx),
841 ActiveView::Configuration => {
842 if let Some(configuration) = self.configuration.as_ref() {
843 configuration.focus_handle(cx)
844 } else {
845 cx.focus_handle()
846 }
847 }
848 }
849 }
850}
851
852impl EventEmitter<PanelEvent> for AssistantPanel {}
853
854impl Panel for AssistantPanel {
855 fn persistent_name() -> &'static str {
856 "AgentPanel"
857 }
858
859 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
860 match AssistantSettings::get_global(cx).dock {
861 AssistantDockPosition::Left => DockPosition::Left,
862 AssistantDockPosition::Bottom => DockPosition::Bottom,
863 AssistantDockPosition::Right => DockPosition::Right,
864 }
865 }
866
867 fn position_is_valid(&self, _: DockPosition) -> bool {
868 true
869 }
870
871 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
872 settings::update_settings_file::<AssistantSettings>(
873 self.fs.clone(),
874 cx,
875 move |settings, _| {
876 let dock = match position {
877 DockPosition::Left => AssistantDockPosition::Left,
878 DockPosition::Bottom => AssistantDockPosition::Bottom,
879 DockPosition::Right => AssistantDockPosition::Right,
880 };
881 settings.set_dock(dock);
882 },
883 );
884 }
885
886 fn size(&self, window: &Window, cx: &App) -> Pixels {
887 let settings = AssistantSettings::get_global(cx);
888 match self.position(window, cx) {
889 DockPosition::Left | DockPosition::Right => {
890 self.width.unwrap_or(settings.default_width)
891 }
892 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
893 }
894 }
895
896 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
897 match self.position(window, cx) {
898 DockPosition::Left | DockPosition::Right => self.width = size,
899 DockPosition::Bottom => self.height = size,
900 }
901 cx.notify();
902 }
903
904 fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
905
906 fn remote_id() -> Option<proto::PanelId> {
907 Some(proto::PanelId::AssistantPanel)
908 }
909
910 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
911 (self.enabled(cx) && AssistantSettings::get_global(cx).button)
912 .then_some(IconName::ZedAssistant)
913 }
914
915 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
916 Some("Agent Panel")
917 }
918
919 fn toggle_action(&self) -> Box<dyn Action> {
920 Box::new(ToggleFocus)
921 }
922
923 fn activation_priority(&self) -> u32 {
924 3
925 }
926
927 fn enabled(&self, cx: &App) -> bool {
928 AssistantSettings::get_global(cx).enabled
929 }
930}
931
932impl AssistantPanel {
933 fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
934 const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
935
936 let content = match &self.active_view {
937 ActiveView::Thread {
938 change_title_editor,
939 ..
940 } => {
941 let active_thread = self.thread.read(cx);
942 let is_empty = active_thread.is_empty();
943
944 let summary = active_thread.summary(cx);
945
946 if is_empty {
947 Label::new(Thread::DEFAULT_SUMMARY.clone())
948 .truncate()
949 .ml_2()
950 .into_any_element()
951 } else if summary.is_none() {
952 Label::new(LOADING_SUMMARY_PLACEHOLDER)
953 .ml_2()
954 .truncate()
955 .into_any_element()
956 } else {
957 div()
958 .ml_2()
959 .w_full()
960 .child(change_title_editor.clone())
961 .into_any_element()
962 }
963 }
964 ActiveView::PromptEditor { context_editor } => {
965 let title = SharedString::from(context_editor.read(cx).title(cx).to_string());
966 Label::new(title).ml_2().truncate().into_any_element()
967 }
968 ActiveView::History => Label::new("History").truncate().into_any_element(),
969 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
970 };
971
972 h_flex()
973 .key_context("TitleEditor")
974 .id("TitleEditor")
975 .flex_grow()
976 .w_full()
977 .max_w_full()
978 .overflow_x_scroll()
979 .child(content)
980 .into_any()
981 }
982
983 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
984 let active_thread = self.thread.read(cx);
985 let thread = active_thread.thread().read(cx);
986 let thread_id = thread.id().clone();
987 let is_empty = active_thread.is_empty();
988 let is_history = matches!(self.active_view, ActiveView::History);
989
990 let show_token_count = match &self.active_view {
991 ActiveView::Thread { .. } => !is_empty,
992 ActiveView::PromptEditor { .. } => true,
993 _ => false,
994 };
995
996 let focus_handle = self.focus_handle(cx);
997
998 let go_back_button = match &self.active_view {
999 ActiveView::History | ActiveView::Configuration => Some(
1000 div().pl_1().child(
1001 IconButton::new("go-back", IconName::ArrowLeft)
1002 .icon_size(IconSize::Small)
1003 .on_click(cx.listener(|this, _, window, cx| {
1004 this.go_back(&workspace::GoBack, window, cx);
1005 }))
1006 .tooltip({
1007 let focus_handle = focus_handle.clone();
1008 move |window, cx| {
1009 Tooltip::for_action_in(
1010 "Go Back",
1011 &workspace::GoBack,
1012 &focus_handle,
1013 window,
1014 cx,
1015 )
1016 }
1017 }),
1018 ),
1019 ),
1020 _ => None,
1021 };
1022
1023 h_flex()
1024 .id("assistant-toolbar")
1025 .h(Tab::container_height(cx))
1026 .max_w_full()
1027 .flex_none()
1028 .justify_between()
1029 .gap_2()
1030 .bg(cx.theme().colors().tab_bar_background)
1031 .border_b_1()
1032 .border_color(cx.theme().colors().border)
1033 .child(
1034 h_flex()
1035 .w_full()
1036 .gap_1()
1037 .children(go_back_button)
1038 .child(self.render_title_view(window, cx)),
1039 )
1040 .child(
1041 h_flex()
1042 .h_full()
1043 .gap_2()
1044 .when(show_token_count, |parent|
1045 parent.children(self.render_token_count(&thread, cx))
1046 )
1047 .child(
1048 h_flex()
1049 .h_full()
1050 .gap(DynamicSpacing::Base02.rems(cx))
1051 .px(DynamicSpacing::Base08.rems(cx))
1052 .border_l_1()
1053 .border_color(cx.theme().colors().border)
1054 .child(
1055 IconButton::new("new", IconName::Plus)
1056 .icon_size(IconSize::Small)
1057 .style(ButtonStyle::Subtle)
1058 .tooltip(move |window, cx| {
1059 Tooltip::for_action_in(
1060 "New Thread",
1061 &NewThread::default(),
1062 &focus_handle,
1063 window,
1064 cx,
1065 )
1066 })
1067 .on_click(move |_event, window, cx| {
1068 window.dispatch_action(
1069 NewThread::default().boxed_clone(),
1070 cx,
1071 );
1072 }),
1073 )
1074 .child(
1075 IconButton::new("open-history", IconName::HistoryRerun)
1076 .icon_size(IconSize::Small)
1077 .toggle_state(is_history)
1078 .selected_icon_color(Color::Accent)
1079 .tooltip({
1080 let focus_handle = self.focus_handle(cx);
1081 move |window, cx| {
1082 Tooltip::for_action_in(
1083 "History",
1084 &OpenHistory,
1085 &focus_handle,
1086 window,
1087 cx,
1088 )
1089 }
1090 })
1091 .on_click(move |_event, window, cx| {
1092 window.dispatch_action(OpenHistory.boxed_clone(), cx);
1093 }),
1094 )
1095 .child(
1096 PopoverMenu::new("assistant-menu")
1097 .trigger_with_tooltip(
1098 IconButton::new("new", IconName::Ellipsis)
1099 .icon_size(IconSize::Small)
1100 .style(ButtonStyle::Subtle),
1101 Tooltip::text("Toggle Agent Menu"),
1102 )
1103 .anchor(Corner::TopRight)
1104 .with_handle(self.assistant_dropdown_menu_handle.clone())
1105 .menu(move |window, cx| {
1106 Some(ContextMenu::build(
1107 window,
1108 cx,
1109 |menu, _window, _cx| {
1110 menu
1111 .when(!is_empty, |menu| {
1112 menu.action(
1113 "Start New From Summary",
1114 Box::new(NewThread {
1115 from_thread_id: Some(thread_id.clone()),
1116 }),
1117 ).separator()
1118 })
1119 .action(
1120 "New Text Thread",
1121 NewTextThread.boxed_clone(),
1122 )
1123 .action("Prompt Library", Box::new(OpenPromptLibrary::default()))
1124 .action("Settings", Box::new(OpenConfiguration))
1125 .separator()
1126 .action(
1127 "Install MCPs",
1128 Box::new(zed_actions::Extensions {
1129 category_filter: Some(
1130 zed_actions::ExtensionCategoryFilter::ContextServers,
1131 ),
1132 }),
1133 )
1134 },
1135 ))
1136 }),
1137 ),
1138 ),
1139 )
1140 }
1141
1142 fn render_token_count(&self, thread: &Thread, cx: &App) -> Option<AnyElement> {
1143 let is_generating = thread.is_generating();
1144 let message_editor = self.message_editor.read(cx);
1145
1146 let conversation_token_usage = thread.total_token_usage(cx);
1147 let (total_token_usage, is_estimating) = if let Some((editing_message_id, unsent_tokens)) =
1148 self.thread.read(cx).editing_message_id()
1149 {
1150 let combined = thread
1151 .token_usage_up_to_message(editing_message_id, cx)
1152 .add(unsent_tokens);
1153
1154 (combined, unsent_tokens > 0)
1155 } else {
1156 let unsent_tokens = message_editor.last_estimated_token_count().unwrap_or(0);
1157 let combined = conversation_token_usage.add(unsent_tokens);
1158
1159 (combined, unsent_tokens > 0)
1160 };
1161
1162 let is_waiting_to_update_token_count = message_editor.is_waiting_to_update_token_count();
1163
1164 match &self.active_view {
1165 ActiveView::Thread { .. } => {
1166 if total_token_usage.total == 0 {
1167 return None;
1168 }
1169
1170 let token_color = match total_token_usage.ratio() {
1171 TokenUsageRatio::Normal if is_estimating => Color::Default,
1172 TokenUsageRatio::Normal => Color::Muted,
1173 TokenUsageRatio::Warning => Color::Warning,
1174 TokenUsageRatio::Exceeded => Color::Error,
1175 };
1176
1177 let token_count = h_flex()
1178 .id("token-count")
1179 .flex_shrink_0()
1180 .gap_0p5()
1181 .when(!is_generating && is_estimating, |parent| {
1182 parent
1183 .child(
1184 h_flex()
1185 .mr_1()
1186 .size_2p5()
1187 .justify_center()
1188 .rounded_full()
1189 .bg(cx.theme().colors().text.opacity(0.1))
1190 .child(
1191 div().size_1().rounded_full().bg(cx.theme().colors().text),
1192 ),
1193 )
1194 .tooltip(move |window, cx| {
1195 Tooltip::with_meta(
1196 "Estimated New Token Count",
1197 None,
1198 format!(
1199 "Current Conversation Tokens: {}",
1200 humanize_token_count(conversation_token_usage.total)
1201 ),
1202 window,
1203 cx,
1204 )
1205 })
1206 })
1207 .child(
1208 Label::new(humanize_token_count(total_token_usage.total))
1209 .size(LabelSize::Small)
1210 .color(token_color)
1211 .map(|label| {
1212 if is_generating || is_waiting_to_update_token_count {
1213 label
1214 .with_animation(
1215 "used-tokens-label",
1216 Animation::new(Duration::from_secs(2))
1217 .repeat()
1218 .with_easing(pulsating_between(0.6, 1.)),
1219 |label, delta| label.alpha(delta),
1220 )
1221 .into_any()
1222 } else {
1223 label.into_any_element()
1224 }
1225 }),
1226 )
1227 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1228 .child(
1229 Label::new(humanize_token_count(total_token_usage.max))
1230 .size(LabelSize::Small)
1231 .color(Color::Muted),
1232 )
1233 .into_any();
1234
1235 Some(token_count)
1236 }
1237 ActiveView::PromptEditor { context_editor } => {
1238 let element = render_remaining_tokens(context_editor, cx)?;
1239
1240 Some(element.into_any_element())
1241 }
1242 _ => None,
1243 }
1244 }
1245
1246 fn render_active_thread_or_empty_state(
1247 &self,
1248 window: &mut Window,
1249 cx: &mut Context<Self>,
1250 ) -> AnyElement {
1251 if self.thread.read(cx).is_empty() {
1252 return self
1253 .render_thread_empty_state(window, cx)
1254 .into_any_element();
1255 }
1256
1257 self.thread.clone().into_any_element()
1258 }
1259
1260 fn configuration_error(&self, cx: &App) -> Option<ConfigurationError> {
1261 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1262 return Some(ConfigurationError::NoProvider);
1263 };
1264
1265 if !model.provider.is_authenticated(cx) {
1266 return Some(ConfigurationError::ProviderNotAuthenticated);
1267 }
1268
1269 if model.provider.must_accept_terms(cx) {
1270 return Some(ConfigurationError::ProviderPendingTermsAcceptance(
1271 model.provider,
1272 ));
1273 }
1274
1275 None
1276 }
1277
1278 fn render_thread_empty_state(
1279 &self,
1280 window: &mut Window,
1281 cx: &mut Context<Self>,
1282 ) -> impl IntoElement {
1283 let recent_history = self
1284 .history_store
1285 .update(cx, |this, cx| this.recent_entries(6, cx));
1286
1287 let configuration_error = self.configuration_error(cx);
1288 let no_error = configuration_error.is_none();
1289 let focus_handle = self.focus_handle(cx);
1290
1291 v_flex()
1292 .size_full()
1293 .when(recent_history.is_empty(), |this| {
1294 let configuration_error_ref = &configuration_error;
1295 this.child(
1296 v_flex()
1297 .size_full()
1298 .max_w_80()
1299 .mx_auto()
1300 .justify_center()
1301 .items_center()
1302 .gap_1()
1303 .child(
1304 h_flex().child(
1305 Headline::new("Welcome to the Agent Panel")
1306 ),
1307 )
1308 .when(no_error, |parent| {
1309 parent
1310 .child(
1311 h_flex().child(
1312 Label::new("Ask and build anything.")
1313 .color(Color::Muted)
1314 .mb_2p5(),
1315 ),
1316 )
1317 .child(
1318 Button::new("new-thread", "Start New Thread")
1319 .icon(IconName::Plus)
1320 .icon_position(IconPosition::Start)
1321 .icon_size(IconSize::Small)
1322 .icon_color(Color::Muted)
1323 .full_width()
1324 .key_binding(KeyBinding::for_action_in(
1325 &NewThread::default(),
1326 &focus_handle,
1327 window,
1328 cx,
1329 ))
1330 .on_click(|_event, window, cx| {
1331 window.dispatch_action(NewThread::default().boxed_clone(), cx)
1332 }),
1333 )
1334 .child(
1335 Button::new("context", "Add Context")
1336 .icon(IconName::FileCode)
1337 .icon_position(IconPosition::Start)
1338 .icon_size(IconSize::Small)
1339 .icon_color(Color::Muted)
1340 .full_width()
1341 .key_binding(KeyBinding::for_action_in(
1342 &ToggleContextPicker,
1343 &focus_handle,
1344 window,
1345 cx,
1346 ))
1347 .on_click(|_event, window, cx| {
1348 window.dispatch_action(ToggleContextPicker.boxed_clone(), cx)
1349 }),
1350 )
1351 .child(
1352 Button::new("mode", "Switch Model")
1353 .icon(IconName::DatabaseZap)
1354 .icon_position(IconPosition::Start)
1355 .icon_size(IconSize::Small)
1356 .icon_color(Color::Muted)
1357 .full_width()
1358 .key_binding(KeyBinding::for_action_in(
1359 &ToggleModelSelector,
1360 &focus_handle,
1361 window,
1362 cx,
1363 ))
1364 .on_click(|_event, window, cx| {
1365 window.dispatch_action(ToggleModelSelector.boxed_clone(), cx)
1366 }),
1367 )
1368 .child(
1369 Button::new("settings", "View Settings")
1370 .icon(IconName::Settings)
1371 .icon_position(IconPosition::Start)
1372 .icon_size(IconSize::Small)
1373 .icon_color(Color::Muted)
1374 .full_width()
1375 .key_binding(KeyBinding::for_action_in(
1376 &OpenConfiguration,
1377 &focus_handle,
1378 window,
1379 cx,
1380 ))
1381 .on_click(|_event, window, cx| {
1382 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
1383 }),
1384 )
1385 })
1386 .map(|parent| {
1387 match configuration_error_ref {
1388 Some(ConfigurationError::ProviderNotAuthenticated)
1389 | Some(ConfigurationError::NoProvider) => {
1390 parent
1391 .child(
1392 h_flex().child(
1393 Label::new("To start using the agent, configure at least one LLM provider.")
1394 .color(Color::Muted)
1395 .mb_2p5()
1396 )
1397 )
1398 .child(
1399 Button::new("settings", "Configure a Provider")
1400 .icon(IconName::Settings)
1401 .icon_position(IconPosition::Start)
1402 .icon_size(IconSize::Small)
1403 .icon_color(Color::Muted)
1404 .full_width()
1405 .key_binding(KeyBinding::for_action_in(
1406 &OpenConfiguration,
1407 &focus_handle,
1408 window,
1409 cx,
1410 ))
1411 .on_click(|_event, window, cx| {
1412 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
1413 }),
1414 )
1415 }
1416 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
1417 parent.children(
1418 provider.render_accept_terms(
1419 LanguageModelProviderTosView::ThreadFreshStart,
1420 cx,
1421 ),
1422 )
1423 }
1424 None => parent,
1425 }
1426 })
1427 )
1428 })
1429 .when(!recent_history.is_empty(), |parent| {
1430 let focus_handle = focus_handle.clone();
1431 let configuration_error_ref = &configuration_error;
1432
1433 parent
1434 .overflow_hidden()
1435 .p_1p5()
1436 .justify_end()
1437 .gap_1()
1438 .child(
1439 h_flex()
1440 .pl_1p5()
1441 .pb_1()
1442 .w_full()
1443 .justify_between()
1444 .border_b_1()
1445 .border_color(cx.theme().colors().border_variant)
1446 .child(
1447 Label::new("Past Interactions")
1448 .size(LabelSize::Small)
1449 .color(Color::Muted),
1450 )
1451 .child(
1452 Button::new("view-history", "View All")
1453 .style(ButtonStyle::Subtle)
1454 .label_size(LabelSize::Small)
1455 .key_binding(
1456 KeyBinding::for_action_in(
1457 &OpenHistory,
1458 &self.focus_handle(cx),
1459 window,
1460 cx,
1461 ).map(|kb| kb.size(rems_from_px(12.))),
1462 )
1463 .on_click(move |_event, window, cx| {
1464 window.dispatch_action(OpenHistory.boxed_clone(), cx);
1465 }),
1466 ),
1467 )
1468 .child(
1469 v_flex()
1470 .gap_1()
1471 .children(
1472 recent_history.into_iter().map(|entry| {
1473 // TODO: Add keyboard navigation.
1474 match entry {
1475 HistoryEntry::Thread(thread) => {
1476 PastThread::new(thread, cx.entity().downgrade(), false, vec![])
1477 .into_any_element()
1478 }
1479 HistoryEntry::Context(context) => {
1480 PastContext::new(context, cx.entity().downgrade(), false, vec![])
1481 .into_any_element()
1482 }
1483 }
1484 }),
1485 )
1486 )
1487 .map(|parent| {
1488 match configuration_error_ref {
1489 Some(ConfigurationError::ProviderNotAuthenticated)
1490 | Some(ConfigurationError::NoProvider) => {
1491 parent
1492 .child(
1493 Banner::new()
1494 .severity(ui::Severity::Warning)
1495 .children(
1496 Label::new(
1497 "Configure at least one LLM provider to start using the panel.",
1498 )
1499 .size(LabelSize::Small),
1500 )
1501 .action_slot(
1502 Button::new("settings", "Configure Provider")
1503 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
1504 .label_size(LabelSize::Small)
1505 .key_binding(
1506 KeyBinding::for_action_in(
1507 &OpenConfiguration,
1508 &focus_handle,
1509 window,
1510 cx,
1511 )
1512 .map(|kb| kb.size(rems_from_px(12.))),
1513 )
1514 .on_click(|_event, window, cx| {
1515 window.dispatch_action(
1516 OpenConfiguration.boxed_clone(),
1517 cx,
1518 )
1519 }),
1520 ),
1521 )
1522 }
1523 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
1524 parent
1525 .child(
1526 Banner::new()
1527 .severity(ui::Severity::Warning)
1528 .children(
1529 h_flex()
1530 .w_full()
1531 .children(
1532 provider.render_accept_terms(
1533 LanguageModelProviderTosView::ThreadtEmptyState,
1534 cx,
1535 ),
1536 ),
1537 ),
1538 )
1539 }
1540 None => parent,
1541 }
1542 })
1543 })
1544 }
1545
1546 fn render_usage_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1547 let usage = self.thread.read(cx).last_usage()?;
1548
1549 Some(UsageBanner::new(zed_llm_client::Plan::ZedProTrial, usage.amount).into_any_element())
1550 }
1551
1552 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1553 let last_error = self.thread.read(cx).last_error()?;
1554
1555 Some(
1556 div()
1557 .absolute()
1558 .right_3()
1559 .bottom_12()
1560 .max_w_96()
1561 .py_2()
1562 .px_3()
1563 .elevation_2(cx)
1564 .occlude()
1565 .child(match last_error {
1566 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
1567 ThreadError::MaxMonthlySpendReached => {
1568 self.render_max_monthly_spend_reached_error(cx)
1569 }
1570 ThreadError::ModelRequestLimitReached { plan } => {
1571 self.render_model_request_limit_reached_error(plan, cx)
1572 }
1573 ThreadError::Message { header, message } => {
1574 self.render_error_message(header, message, cx)
1575 }
1576 })
1577 .into_any(),
1578 )
1579 }
1580
1581 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
1582 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.";
1583
1584 v_flex()
1585 .gap_0p5()
1586 .child(
1587 h_flex()
1588 .gap_1p5()
1589 .items_center()
1590 .child(Icon::new(IconName::XCircle).color(Color::Error))
1591 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
1592 )
1593 .child(
1594 div()
1595 .id("error-message")
1596 .max_h_24()
1597 .overflow_y_scroll()
1598 .child(Label::new(ERROR_MESSAGE)),
1599 )
1600 .child(
1601 h_flex()
1602 .justify_end()
1603 .mt_1()
1604 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
1605 |this, _, _, cx| {
1606 this.thread.update(cx, |this, _cx| {
1607 this.clear_last_error();
1608 });
1609
1610 cx.open_url(&zed_urls::account_url(cx));
1611 cx.notify();
1612 },
1613 )))
1614 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1615 |this, _, _, cx| {
1616 this.thread.update(cx, |this, _cx| {
1617 this.clear_last_error();
1618 });
1619
1620 cx.notify();
1621 },
1622 ))),
1623 )
1624 .into_any()
1625 }
1626
1627 fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
1628 const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
1629
1630 v_flex()
1631 .gap_0p5()
1632 .child(
1633 h_flex()
1634 .gap_1p5()
1635 .items_center()
1636 .child(Icon::new(IconName::XCircle).color(Color::Error))
1637 .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
1638 )
1639 .child(
1640 div()
1641 .id("error-message")
1642 .max_h_24()
1643 .overflow_y_scroll()
1644 .child(Label::new(ERROR_MESSAGE)),
1645 )
1646 .child(
1647 h_flex()
1648 .justify_end()
1649 .mt_1()
1650 .child(
1651 Button::new("subscribe", "Update Monthly Spend Limit").on_click(
1652 cx.listener(|this, _, _, cx| {
1653 this.thread.update(cx, |this, _cx| {
1654 this.clear_last_error();
1655 });
1656
1657 cx.open_url(&zed_urls::account_url(cx));
1658 cx.notify();
1659 }),
1660 ),
1661 )
1662 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1663 |this, _, _, cx| {
1664 this.thread.update(cx, |this, _cx| {
1665 this.clear_last_error();
1666 });
1667
1668 cx.notify();
1669 },
1670 ))),
1671 )
1672 .into_any()
1673 }
1674
1675 fn render_model_request_limit_reached_error(
1676 &self,
1677 plan: Plan,
1678 cx: &mut Context<Self>,
1679 ) -> AnyElement {
1680 let error_message = match plan {
1681 Plan::ZedPro => {
1682 "Model request limit reached. Upgrade to usage-based billing for more requests."
1683 }
1684 Plan::ZedProTrial => {
1685 "Model request limit reached. Upgrade to Zed Pro for more requests."
1686 }
1687 Plan::Free => "Model request limit reached. Upgrade to Zed Pro for more requests.",
1688 };
1689 let call_to_action = match plan {
1690 Plan::ZedPro => "Upgrade to usage-based billing",
1691 Plan::ZedProTrial => "Upgrade to Zed Pro",
1692 Plan::Free => "Upgrade to Zed Pro",
1693 };
1694
1695 v_flex()
1696 .gap_0p5()
1697 .child(
1698 h_flex()
1699 .gap_1p5()
1700 .items_center()
1701 .child(Icon::new(IconName::XCircle).color(Color::Error))
1702 .child(Label::new("Model Request Limit Reached").weight(FontWeight::MEDIUM)),
1703 )
1704 .child(
1705 div()
1706 .id("error-message")
1707 .max_h_24()
1708 .overflow_y_scroll()
1709 .child(Label::new(error_message)),
1710 )
1711 .child(
1712 h_flex()
1713 .justify_end()
1714 .mt_1()
1715 .child(
1716 Button::new("subscribe", call_to_action).on_click(cx.listener(
1717 |this, _, _, cx| {
1718 this.thread.update(cx, |this, _cx| {
1719 this.clear_last_error();
1720 });
1721
1722 cx.open_url(&zed_urls::account_url(cx));
1723 cx.notify();
1724 },
1725 )),
1726 )
1727 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1728 |this, _, _, cx| {
1729 this.thread.update(cx, |this, _cx| {
1730 this.clear_last_error();
1731 });
1732
1733 cx.notify();
1734 },
1735 ))),
1736 )
1737 .into_any()
1738 }
1739
1740 fn render_error_message(
1741 &self,
1742 header: SharedString,
1743 message: SharedString,
1744 cx: &mut Context<Self>,
1745 ) -> AnyElement {
1746 v_flex()
1747 .gap_0p5()
1748 .child(
1749 h_flex()
1750 .gap_1p5()
1751 .items_center()
1752 .child(Icon::new(IconName::XCircle).color(Color::Error))
1753 .child(Label::new(header).weight(FontWeight::MEDIUM)),
1754 )
1755 .child(
1756 div()
1757 .id("error-message")
1758 .max_h_32()
1759 .overflow_y_scroll()
1760 .child(Label::new(message)),
1761 )
1762 .child(
1763 h_flex()
1764 .justify_end()
1765 .mt_1()
1766 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1767 |this, _, _, cx| {
1768 this.thread.update(cx, |this, _cx| {
1769 this.clear_last_error();
1770 });
1771
1772 cx.notify();
1773 },
1774 ))),
1775 )
1776 .into_any()
1777 }
1778
1779 fn key_context(&self) -> KeyContext {
1780 let mut key_context = KeyContext::new_with_defaults();
1781 key_context.add("AgentPanel");
1782 if matches!(self.active_view, ActiveView::PromptEditor { .. }) {
1783 key_context.add("prompt_editor");
1784 }
1785 key_context
1786 }
1787}
1788
1789impl Render for AssistantPanel {
1790 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1791 v_flex()
1792 .key_context(self.key_context())
1793 .justify_between()
1794 .size_full()
1795 .on_action(cx.listener(Self::cancel))
1796 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
1797 this.new_thread(action, window, cx);
1798 }))
1799 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
1800 this.open_history(window, cx);
1801 }))
1802 .on_action(cx.listener(|this, _: &OpenConfiguration, window, cx| {
1803 this.open_configuration(window, cx);
1804 }))
1805 .on_action(cx.listener(Self::open_active_thread_as_markdown))
1806 .on_action(cx.listener(Self::deploy_prompt_library))
1807 .on_action(cx.listener(Self::open_agent_diff))
1808 .on_action(cx.listener(Self::go_back))
1809 .child(self.render_toolbar(window, cx))
1810 .map(|parent| match &self.active_view {
1811 ActiveView::Thread { .. } => parent
1812 .child(self.render_active_thread_or_empty_state(window, cx))
1813 .children(self.render_usage_banner(cx))
1814 .child(h_flex().child(self.message_editor.clone()))
1815 .children(self.render_last_error(cx)),
1816 ActiveView::History => parent.child(self.history.clone()),
1817 ActiveView::PromptEditor { context_editor } => parent.child(context_editor.clone()),
1818 ActiveView::Configuration => parent.children(self.configuration.clone()),
1819 })
1820 }
1821}
1822
1823struct PromptLibraryInlineAssist {
1824 workspace: WeakEntity<Workspace>,
1825}
1826
1827impl PromptLibraryInlineAssist {
1828 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
1829 Self { workspace }
1830 }
1831}
1832
1833impl prompt_library::InlineAssistDelegate for PromptLibraryInlineAssist {
1834 fn assist(
1835 &self,
1836 prompt_editor: &Entity<Editor>,
1837 _initial_prompt: Option<String>,
1838 window: &mut Window,
1839 cx: &mut Context<PromptLibrary>,
1840 ) {
1841 InlineAssistant::update_global(cx, |assistant, cx| {
1842 let Some(project) = self
1843 .workspace
1844 .upgrade()
1845 .map(|workspace| workspace.read(cx).project().downgrade())
1846 else {
1847 return;
1848 };
1849 assistant.assist(
1850 &prompt_editor,
1851 self.workspace.clone(),
1852 project,
1853 None,
1854 window,
1855 cx,
1856 )
1857 })
1858 }
1859
1860 fn focus_assistant_panel(
1861 &self,
1862 workspace: &mut Workspace,
1863 window: &mut Window,
1864 cx: &mut Context<Workspace>,
1865 ) -> bool {
1866 workspace
1867 .focus_panel::<AssistantPanel>(window, cx)
1868 .is_some()
1869 }
1870}
1871
1872pub struct ConcreteAssistantPanelDelegate;
1873
1874impl AssistantPanelDelegate for ConcreteAssistantPanelDelegate {
1875 fn active_context_editor(
1876 &self,
1877 workspace: &mut Workspace,
1878 _window: &mut Window,
1879 cx: &mut Context<Workspace>,
1880 ) -> Option<Entity<ContextEditor>> {
1881 let panel = workspace.panel::<AssistantPanel>(cx)?;
1882 panel.read(cx).active_context_editor()
1883 }
1884
1885 fn open_saved_context(
1886 &self,
1887 workspace: &mut Workspace,
1888 path: std::path::PathBuf,
1889 window: &mut Window,
1890 cx: &mut Context<Workspace>,
1891 ) -> Task<Result<()>> {
1892 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1893 return Task::ready(Err(anyhow!("Agent panel not found")));
1894 };
1895
1896 panel.update(cx, |panel, cx| {
1897 panel.open_saved_prompt_editor(path, window, cx)
1898 })
1899 }
1900
1901 fn open_remote_context(
1902 &self,
1903 _workspace: &mut Workspace,
1904 _context_id: assistant_context_editor::ContextId,
1905 _window: &mut Window,
1906 _cx: &mut Context<Workspace>,
1907 ) -> Task<Result<Entity<ContextEditor>>> {
1908 Task::ready(Err(anyhow!("opening remote context not implemented")))
1909 }
1910
1911 fn quote_selection(
1912 &self,
1913 workspace: &mut Workspace,
1914 selection_ranges: Vec<Range<Anchor>>,
1915 buffer: Entity<MultiBuffer>,
1916 window: &mut Window,
1917 cx: &mut Context<Workspace>,
1918 ) {
1919 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1920 return;
1921 };
1922
1923 if !panel.focus_handle(cx).contains_focused(window, cx) {
1924 workspace.toggle_panel_focus::<AssistantPanel>(window, cx);
1925 }
1926
1927 panel.update(cx, |_, cx| {
1928 // Wait to create a new context until the workspace is no longer
1929 // being updated.
1930 cx.defer_in(window, move |panel, window, cx| {
1931 if panel.has_active_thread() {
1932 panel.thread.update(cx, |thread, cx| {
1933 thread.context_store().update(cx, |store, cx| {
1934 let buffer = buffer.read(cx);
1935 let selection_ranges = selection_ranges
1936 .into_iter()
1937 .flat_map(|range| {
1938 let (start_buffer, start) =
1939 buffer.text_anchor_for_position(range.start, cx)?;
1940 let (end_buffer, end) =
1941 buffer.text_anchor_for_position(range.end, cx)?;
1942 if start_buffer != end_buffer {
1943 return None;
1944 }
1945 Some((start_buffer, start..end))
1946 })
1947 .collect::<Vec<_>>();
1948
1949 for (buffer, range) in selection_ranges {
1950 store.add_excerpt(range, buffer, cx).detach_and_log_err(cx);
1951 }
1952 })
1953 })
1954 } else if let Some(context_editor) = panel.active_context_editor() {
1955 let snapshot = buffer.read(cx).snapshot(cx);
1956 let selection_ranges = selection_ranges
1957 .into_iter()
1958 .map(|range| range.to_point(&snapshot))
1959 .collect::<Vec<_>>();
1960
1961 context_editor.update(cx, |context_editor, cx| {
1962 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
1963 });
1964 }
1965 });
1966 });
1967 }
1968}