1use std::ops::Range;
2use std::path::Path;
3use std::sync::Arc;
4use std::time::Duration;
5
6use db::kvp::KEY_VALUE_STORE;
7use markdown::Markdown;
8use serde::{Deserialize, Serialize};
9
10use anyhow::{Result, anyhow};
11use assistant_context_editor::{
12 AssistantContext, AssistantPanelDelegate, ConfigurationError, ContextEditor, ContextEvent,
13 SlashCommandCompletionProvider, humanize_token_count, make_lsp_adapter_delegate,
14 render_remaining_tokens,
15};
16use assistant_settings::{AssistantDockPosition, AssistantSettings};
17use assistant_slash_command::SlashCommandWorkingSet;
18use assistant_tool::ToolWorkingSet;
19
20use client::{UserStore, zed_urls};
21use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
22use fs::Fs;
23use gpui::{
24 Action, Animation, AnimationExt as _, AnyElement, App, AsyncWindowContext, ClipboardItem,
25 Corner, DismissEvent, Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable, FontWeight,
26 KeyContext, Pixels, Subscription, Task, UpdateGlobal, WeakEntity, linear_color_stop,
27 linear_gradient, prelude::*, pulsating_between,
28};
29use language::LanguageRegistry;
30use language_model::{
31 LanguageModelProviderTosView, LanguageModelRegistry, RequestUsage, ZED_CLOUD_PROVIDER_ID,
32};
33use language_model_selector::ToggleModelSelector;
34use project::{Project, ProjectPath, Worktree};
35use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
36use proto::Plan;
37use rules_library::{RulesLibrary, open_rules_library};
38use search::{BufferSearchBar, buffer_search};
39use settings::{Settings, update_settings_file};
40use theme::ThemeSettings;
41use time::UtcOffset;
42use ui::{
43 Banner, CheckboxWithLabel, ContextMenu, KeyBinding, PopoverMenu, PopoverMenuHandle,
44 ProgressBar, Tab, Tooltip, Vector, VectorName, prelude::*,
45};
46use util::{ResultExt as _, maybe};
47use workspace::dock::{DockPosition, Panel, PanelEvent};
48use workspace::{CollaboratorId, DraggedSelection, DraggedTab, ToolbarItemView, Workspace};
49use zed_actions::agent::OpenConfiguration;
50use zed_actions::assistant::{OpenRulesLibrary, ToggleFocus};
51use zed_actions::{DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize};
52use zed_llm_client::UsageLimit;
53
54use crate::active_thread::{self, ActiveThread, ActiveThreadEvent};
55use crate::agent_diff::AgentDiff;
56use crate::assistant_configuration::{AssistantConfiguration, AssistantConfigurationEvent};
57use crate::history_store::{HistoryEntry, HistoryStore, RecentEntry};
58use crate::message_editor::{MessageEditor, MessageEditorEvent};
59use crate::thread::{Thread, ThreadError, ThreadId, TokenUsageRatio};
60use crate::thread_history::{EntryTimeFormat, PastContext, PastThread, ThreadHistory};
61use crate::thread_store::ThreadStore;
62use crate::{
63 AddContextServer, AgentDiffPane, ContextStore, DeleteRecentlyOpenThread, ExpandMessageEditor,
64 Follow, InlineAssistant, NewTextThread, NewThread, OpenActiveThreadAsMarkdown, OpenAgentDiff,
65 OpenHistory, ResetTrialUpsell, TextThreadStore, ThreadEvent, ToggleContextPicker,
66 ToggleNavigationMenu, ToggleOptionsMenu,
67};
68
69const AGENT_PANEL_KEY: &str = "agent_panel";
70
71#[derive(Serialize, Deserialize)]
72struct SerializedAssistantPanel {
73 width: Option<Pixels>,
74}
75
76pub fn init(cx: &mut App) {
77 cx.observe_new(
78 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
79 workspace
80 .register_action(|workspace, action: &NewThread, window, cx| {
81 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
82 panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
83 workspace.focus_panel::<AssistantPanel>(window, cx);
84 }
85 })
86 .register_action(|workspace, _: &OpenHistory, window, cx| {
87 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
88 workspace.focus_panel::<AssistantPanel>(window, cx);
89 panel.update(cx, |panel, cx| panel.open_history(window, cx));
90 }
91 })
92 .register_action(|workspace, _: &OpenConfiguration, window, cx| {
93 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
94 workspace.focus_panel::<AssistantPanel>(window, cx);
95 panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
96 }
97 })
98 .register_action(|workspace, _: &NewTextThread, window, cx| {
99 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
100 workspace.focus_panel::<AssistantPanel>(window, cx);
101 panel.update(cx, |panel, cx| panel.new_prompt_editor(window, cx));
102 }
103 })
104 .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
105 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
106 workspace.focus_panel::<AssistantPanel>(window, cx);
107 panel.update(cx, |panel, cx| {
108 panel.deploy_rules_library(action, window, cx)
109 });
110 }
111 })
112 .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
113 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
114 workspace.focus_panel::<AssistantPanel>(window, cx);
115 let thread = panel.read(cx).thread.read(cx).thread().clone();
116 AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);
117 }
118 })
119 .register_action(|workspace, _: &Follow, window, cx| {
120 workspace.follow(CollaboratorId::Agent, window, cx);
121 })
122 .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
123 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
124 workspace.focus_panel::<AssistantPanel>(window, cx);
125 panel.update(cx, |panel, cx| {
126 panel.message_editor.update(cx, |editor, cx| {
127 editor.expand_message_editor(&ExpandMessageEditor, window, cx);
128 });
129 });
130 }
131 })
132 .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {
133 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
134 workspace.focus_panel::<AssistantPanel>(window, cx);
135 panel.update(cx, |panel, cx| {
136 panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);
137 });
138 }
139 })
140 .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
141 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
142 workspace.focus_panel::<AssistantPanel>(window, cx);
143 panel.update(cx, |panel, cx| {
144 panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
145 });
146 }
147 })
148 .register_action(|_workspace, _: &ResetTrialUpsell, _window, cx| {
149 set_trial_upsell_dismissed(false, cx);
150 });
151 },
152 )
153 .detach();
154}
155
156enum ActiveView {
157 Thread {
158 change_title_editor: Entity<Editor>,
159 thread: WeakEntity<Thread>,
160 _subscriptions: Vec<gpui::Subscription>,
161 },
162 PromptEditor {
163 context_editor: Entity<ContextEditor>,
164 title_editor: Entity<Editor>,
165 buffer_search_bar: Entity<BufferSearchBar>,
166 _subscriptions: Vec<gpui::Subscription>,
167 },
168 History,
169 Configuration,
170}
171
172impl ActiveView {
173 pub fn thread(thread: Entity<Thread>, window: &mut Window, cx: &mut App) -> Self {
174 let summary = thread.read(cx).summary_or_default();
175
176 let editor = cx.new(|cx| {
177 let mut editor = Editor::single_line(window, cx);
178 editor.set_text(summary.clone(), window, cx);
179 editor
180 });
181
182 let subscriptions = vec![
183 window.subscribe(&editor, cx, {
184 {
185 let thread = thread.clone();
186 move |editor, event, window, cx| match event {
187 EditorEvent::BufferEdited => {
188 let new_summary = editor.read(cx).text(cx);
189
190 thread.update(cx, |thread, cx| {
191 thread.set_summary(new_summary, cx);
192 })
193 }
194 EditorEvent::Blurred => {
195 if editor.read(cx).text(cx).is_empty() {
196 let summary = thread.read(cx).summary_or_default();
197
198 editor.update(cx, |editor, cx| {
199 editor.set_text(summary, window, cx);
200 });
201 }
202 }
203 _ => {}
204 }
205 }
206 }),
207 window.subscribe(&thread, cx, {
208 let editor = editor.clone();
209 move |thread, event, window, cx| match event {
210 ThreadEvent::SummaryGenerated => {
211 let summary = thread.read(cx).summary_or_default();
212
213 editor.update(cx, |editor, cx| {
214 editor.set_text(summary, window, cx);
215 })
216 }
217 _ => {}
218 }
219 }),
220 ];
221
222 Self::Thread {
223 change_title_editor: editor,
224 thread: thread.downgrade(),
225 _subscriptions: subscriptions,
226 }
227 }
228
229 pub fn prompt_editor(
230 context_editor: Entity<ContextEditor>,
231 language_registry: Arc<LanguageRegistry>,
232 window: &mut Window,
233 cx: &mut App,
234 ) -> Self {
235 let title = context_editor.read(cx).title(cx).to_string();
236
237 let editor = cx.new(|cx| {
238 let mut editor = Editor::single_line(window, cx);
239 editor.set_text(title, window, cx);
240 editor
241 });
242
243 // This is a workaround for `editor.set_text` emitting a `BufferEdited` event, which would
244 // cause a custom summary to be set. The presence of this custom summary would cause
245 // summarization to not happen.
246 let mut suppress_first_edit = true;
247
248 let subscriptions = vec![
249 window.subscribe(&editor, cx, {
250 {
251 let context_editor = context_editor.clone();
252 move |editor, event, window, cx| match event {
253 EditorEvent::BufferEdited => {
254 if suppress_first_edit {
255 suppress_first_edit = false;
256 return;
257 }
258 let new_summary = editor.read(cx).text(cx);
259
260 context_editor.update(cx, |context_editor, cx| {
261 context_editor
262 .context()
263 .update(cx, |assistant_context, cx| {
264 assistant_context.set_custom_summary(new_summary, cx);
265 })
266 })
267 }
268 EditorEvent::Blurred => {
269 if editor.read(cx).text(cx).is_empty() {
270 let summary = context_editor
271 .read(cx)
272 .context()
273 .read(cx)
274 .summary_or_default();
275
276 editor.update(cx, |editor, cx| {
277 editor.set_text(summary, window, cx);
278 });
279 }
280 }
281 _ => {}
282 }
283 }
284 }),
285 window.subscribe(&context_editor.read(cx).context().clone(), cx, {
286 let editor = editor.clone();
287 move |assistant_context, event, window, cx| match event {
288 ContextEvent::SummaryGenerated => {
289 let summary = assistant_context.read(cx).summary_or_default();
290
291 editor.update(cx, |editor, cx| {
292 editor.set_text(summary, window, cx);
293 })
294 }
295 _ => {}
296 }
297 }),
298 ];
299
300 let buffer_search_bar =
301 cx.new(|cx| BufferSearchBar::new(Some(language_registry), window, cx));
302 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
303 buffer_search_bar.set_active_pane_item(Some(&context_editor), window, cx)
304 });
305
306 Self::PromptEditor {
307 context_editor,
308 title_editor: editor,
309 buffer_search_bar,
310 _subscriptions: subscriptions,
311 }
312 }
313}
314
315pub struct AssistantPanel {
316 workspace: WeakEntity<Workspace>,
317 user_store: Entity<UserStore>,
318 project: Entity<Project>,
319 fs: Arc<dyn Fs>,
320 language_registry: Arc<LanguageRegistry>,
321 thread_store: Entity<ThreadStore>,
322 thread: Entity<ActiveThread>,
323 message_editor: Entity<MessageEditor>,
324 _active_thread_subscriptions: Vec<Subscription>,
325 _default_model_subscription: Subscription,
326 context_store: Entity<TextThreadStore>,
327 prompt_store: Option<Entity<PromptStore>>,
328 inline_assist_context_store: Entity<crate::context_store::ContextStore>,
329 configuration: Option<Entity<AssistantConfiguration>>,
330 configuration_subscription: Option<Subscription>,
331 local_timezone: UtcOffset,
332 active_view: ActiveView,
333 previous_view: Option<ActiveView>,
334 history_store: Entity<HistoryStore>,
335 history: Entity<ThreadHistory>,
336 assistant_dropdown_menu_handle: PopoverMenuHandle<ContextMenu>,
337 assistant_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
338 assistant_navigation_menu: Option<Entity<ContextMenu>>,
339 width: Option<Pixels>,
340 height: Option<Pixels>,
341 pending_serialization: Option<Task<Result<()>>>,
342 hide_trial_upsell: bool,
343 _trial_markdown: Entity<Markdown>,
344}
345
346impl AssistantPanel {
347 fn serialize(&mut self, cx: &mut Context<Self>) {
348 let width = self.width;
349 self.pending_serialization = Some(cx.background_spawn(async move {
350 KEY_VALUE_STORE
351 .write_kvp(
352 AGENT_PANEL_KEY.into(),
353 serde_json::to_string(&SerializedAssistantPanel { width })?,
354 )
355 .await?;
356 anyhow::Ok(())
357 }));
358 }
359 pub fn load(
360 workspace: WeakEntity<Workspace>,
361 prompt_builder: Arc<PromptBuilder>,
362 mut cx: AsyncWindowContext,
363 ) -> Task<Result<Entity<Self>>> {
364 let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
365 cx.spawn(async move |cx| {
366 let prompt_store = match prompt_store {
367 Ok(prompt_store) => prompt_store.await.ok(),
368 Err(_) => None,
369 };
370 let tools = cx.new(|_| ToolWorkingSet::default())?;
371 let thread_store = workspace
372 .update(cx, |workspace, cx| {
373 let project = workspace.project().clone();
374 ThreadStore::load(
375 project,
376 tools.clone(),
377 prompt_store.clone(),
378 prompt_builder.clone(),
379 cx,
380 )
381 })?
382 .await?;
383
384 let slash_commands = Arc::new(SlashCommandWorkingSet::default());
385 let context_store = workspace
386 .update(cx, |workspace, cx| {
387 let project = workspace.project().clone();
388 assistant_context_editor::ContextStore::new(
389 project,
390 prompt_builder.clone(),
391 slash_commands,
392 cx,
393 )
394 })?
395 .await?;
396
397 let serialized_panel = if let Some(panel) = cx
398 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(AGENT_PANEL_KEY) })
399 .await
400 .log_err()
401 .flatten()
402 {
403 Some(serde_json::from_str::<SerializedAssistantPanel>(&panel)?)
404 } else {
405 None
406 };
407
408 let panel = workspace.update_in(cx, |workspace, window, cx| {
409 let panel = cx.new(|cx| {
410 Self::new(
411 workspace,
412 thread_store,
413 context_store,
414 prompt_store,
415 window,
416 cx,
417 )
418 });
419 if let Some(serialized_panel) = serialized_panel {
420 panel.update(cx, |panel, cx| {
421 panel.width = serialized_panel.width.map(|w| w.round());
422 cx.notify();
423 });
424 }
425 panel
426 })?;
427
428 Ok(panel)
429 })
430 }
431
432 fn new(
433 workspace: &Workspace,
434 thread_store: Entity<ThreadStore>,
435 context_store: Entity<TextThreadStore>,
436 prompt_store: Option<Entity<PromptStore>>,
437 window: &mut Window,
438 cx: &mut Context<Self>,
439 ) -> Self {
440 let thread = thread_store.update(cx, |this, cx| this.create_thread(cx));
441 let fs = workspace.app_state().fs.clone();
442 let user_store = workspace.app_state().user_store.clone();
443 let project = workspace.project();
444 let language_registry = project.read(cx).languages().clone();
445 let workspace = workspace.weak_handle();
446 let weak_self = cx.entity().downgrade();
447
448 let message_editor_context_store = cx.new(|_cx| {
449 crate::context_store::ContextStore::new(
450 project.downgrade(),
451 Some(thread_store.downgrade()),
452 )
453 });
454 let inline_assist_context_store = cx.new(|_cx| {
455 crate::context_store::ContextStore::new(
456 project.downgrade(),
457 Some(thread_store.downgrade()),
458 )
459 });
460
461 let message_editor = cx.new(|cx| {
462 MessageEditor::new(
463 fs.clone(),
464 workspace.clone(),
465 user_store.clone(),
466 message_editor_context_store.clone(),
467 prompt_store.clone(),
468 thread_store.downgrade(),
469 context_store.downgrade(),
470 thread.clone(),
471 agent_panel_dock_position(cx),
472 window,
473 cx,
474 )
475 });
476
477 let message_editor_subscription =
478 cx.subscribe(&message_editor, |_, _, event, cx| match event {
479 MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
480 cx.notify();
481 }
482 });
483
484 let thread_id = thread.read(cx).id().clone();
485 let history_store = cx.new(|cx| {
486 HistoryStore::new(
487 thread_store.clone(),
488 context_store.clone(),
489 [RecentEntry::Thread(thread_id, thread.clone())],
490 cx,
491 )
492 });
493
494 cx.observe(&history_store, |_, _, cx| cx.notify()).detach();
495
496 let active_view = ActiveView::thread(thread.clone(), window, cx);
497 let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
498 if let ThreadEvent::MessageAdded(_) = &event {
499 // needed to leave empty state
500 cx.notify();
501 }
502 });
503 let active_thread = cx.new(|cx| {
504 ActiveThread::new(
505 thread.clone(),
506 thread_store.clone(),
507 context_store.clone(),
508 message_editor_context_store.clone(),
509 language_registry.clone(),
510 workspace.clone(),
511 window,
512 cx,
513 )
514 });
515 AgentDiff::set_active_thread(&workspace, &thread, window, cx);
516
517 let active_thread_subscription =
518 cx.subscribe(&active_thread, |_, _, event, cx| match &event {
519 ActiveThreadEvent::EditingMessageTokenCountChanged => {
520 cx.notify();
521 }
522 });
523
524 let weak_panel = weak_self.clone();
525
526 window.defer(cx, move |window, cx| {
527 let panel = weak_panel.clone();
528 let assistant_navigation_menu =
529 ContextMenu::build_persistent(window, cx, move |mut menu, _window, cx| {
530 let recently_opened = panel
531 .update(cx, |this, cx| {
532 this.history_store.update(cx, |history_store, cx| {
533 history_store.recently_opened_entries(cx)
534 })
535 })
536 .unwrap_or_default();
537
538 if !recently_opened.is_empty() {
539 menu = menu.header("Recently Opened");
540
541 for entry in recently_opened.iter() {
542 let summary = entry.summary(cx);
543
544 menu = menu.entry_with_end_slot_on_hover(
545 summary,
546 None,
547 {
548 let panel = panel.clone();
549 let entry = entry.clone();
550 move |window, cx| {
551 panel
552 .update(cx, {
553 let entry = entry.clone();
554 move |this, cx| match entry {
555 RecentEntry::Thread(_, thread) => {
556 this.open_thread(thread, window, cx)
557 }
558 RecentEntry::Context(context) => {
559 let Some(path) = context.read(cx).path()
560 else {
561 return;
562 };
563 this.open_saved_prompt_editor(
564 path.clone(),
565 window,
566 cx,
567 )
568 .detach_and_log_err(cx)
569 }
570 }
571 })
572 .ok();
573 }
574 },
575 IconName::Close,
576 "Close Entry".into(),
577 {
578 let panel = panel.clone();
579 let entry = entry.clone();
580 move |_window, cx| {
581 panel
582 .update(cx, |this, cx| {
583 this.history_store.update(
584 cx,
585 |history_store, cx| {
586 history_store.remove_recently_opened_entry(
587 &entry, cx,
588 );
589 },
590 );
591 })
592 .ok();
593 }
594 },
595 );
596 }
597
598 menu = menu.separator();
599 }
600
601 menu.action("View All", Box::new(OpenHistory))
602 .end_slot_action(DeleteRecentlyOpenThread.boxed_clone())
603 .fixed_width(px(320.).into())
604 .keep_open_on_confirm(false)
605 .key_context("NavigationMenu")
606 });
607 weak_panel
608 .update(cx, |panel, cx| {
609 cx.subscribe_in(
610 &assistant_navigation_menu,
611 window,
612 |_, menu, _: &DismissEvent, window, cx| {
613 menu.update(cx, |menu, _| {
614 menu.clear_selected();
615 });
616 cx.focus_self(window);
617 },
618 )
619 .detach();
620 panel.assistant_navigation_menu = Some(assistant_navigation_menu);
621 })
622 .ok();
623 });
624
625 let _default_model_subscription = cx.subscribe(
626 &LanguageModelRegistry::global(cx),
627 |this, _, event: &language_model::Event, cx| match event {
628 language_model::Event::DefaultModelChanged => {
629 this.thread
630 .read(cx)
631 .thread()
632 .clone()
633 .update(cx, |thread, cx| thread.get_or_init_configured_model(cx));
634 }
635 _ => {}
636 },
637 );
638
639 let trial_markdown = cx.new(|cx| {
640 Markdown::new(
641 include_str!("trial_markdown.md").into(),
642 Some(language_registry.clone()),
643 None,
644 cx,
645 )
646 });
647
648 Self {
649 active_view,
650 workspace,
651 user_store,
652 project: project.clone(),
653 fs: fs.clone(),
654 language_registry,
655 thread_store: thread_store.clone(),
656 thread: active_thread,
657 message_editor,
658 _active_thread_subscriptions: vec![
659 thread_subscription,
660 active_thread_subscription,
661 message_editor_subscription,
662 ],
663 _default_model_subscription,
664 context_store,
665 prompt_store,
666 configuration: None,
667 configuration_subscription: None,
668 local_timezone: UtcOffset::from_whole_seconds(
669 chrono::Local::now().offset().local_minus_utc(),
670 )
671 .unwrap(),
672 inline_assist_context_store,
673 previous_view: None,
674 history_store: history_store.clone(),
675 history: cx.new(|cx| ThreadHistory::new(weak_self, history_store, window, cx)),
676 assistant_dropdown_menu_handle: PopoverMenuHandle::default(),
677 assistant_navigation_menu_handle: PopoverMenuHandle::default(),
678 assistant_navigation_menu: None,
679 width: None,
680 height: None,
681 pending_serialization: None,
682 hide_trial_upsell: false,
683 _trial_markdown: trial_markdown,
684 }
685 }
686
687 pub fn toggle_focus(
688 workspace: &mut Workspace,
689 _: &ToggleFocus,
690 window: &mut Window,
691 cx: &mut Context<Workspace>,
692 ) {
693 if workspace
694 .panel::<Self>(cx)
695 .is_some_and(|panel| panel.read(cx).enabled(cx))
696 {
697 workspace.toggle_panel_focus::<Self>(window, cx);
698 }
699 }
700
701 pub(crate) fn local_timezone(&self) -> UtcOffset {
702 self.local_timezone
703 }
704
705 pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
706 &self.prompt_store
707 }
708
709 pub(crate) fn inline_assist_context_store(
710 &self,
711 ) -> &Entity<crate::context_store::ContextStore> {
712 &self.inline_assist_context_store
713 }
714
715 pub(crate) fn thread_store(&self) -> &Entity<ThreadStore> {
716 &self.thread_store
717 }
718
719 pub(crate) fn text_thread_store(&self) -> &Entity<TextThreadStore> {
720 &self.context_store
721 }
722
723 fn cancel(&mut self, _: &editor::actions::Cancel, window: &mut Window, cx: &mut Context<Self>) {
724 self.thread
725 .update(cx, |thread, cx| thread.cancel_last_completion(window, cx));
726 }
727
728 fn new_thread(&mut self, action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
729 let thread = self
730 .thread_store
731 .update(cx, |this, cx| this.create_thread(cx));
732
733 let thread_view = ActiveView::thread(thread.clone(), window, cx);
734 self.set_active_view(thread_view, window, cx);
735
736 let context_store = cx.new(|_cx| {
737 crate::context_store::ContextStore::new(
738 self.project.downgrade(),
739 Some(self.thread_store.downgrade()),
740 )
741 });
742
743 if let Some(other_thread_id) = action.from_thread_id.clone() {
744 let other_thread_task = self
745 .thread_store
746 .update(cx, |this, cx| this.open_thread(&other_thread_id, cx));
747
748 cx.spawn({
749 let context_store = context_store.clone();
750
751 async move |_panel, cx| {
752 let other_thread = other_thread_task.await?;
753
754 context_store.update(cx, |this, cx| {
755 this.add_thread(other_thread, false, cx);
756 })?;
757 anyhow::Ok(())
758 }
759 })
760 .detach_and_log_err(cx);
761 }
762
763 let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
764 if let ThreadEvent::MessageAdded(_) = &event {
765 // needed to leave empty state
766 cx.notify();
767 }
768 });
769
770 self.thread = cx.new(|cx| {
771 ActiveThread::new(
772 thread.clone(),
773 self.thread_store.clone(),
774 self.context_store.clone(),
775 context_store.clone(),
776 self.language_registry.clone(),
777 self.workspace.clone(),
778 window,
779 cx,
780 )
781 });
782 AgentDiff::set_active_thread(&self.workspace, &thread, window, cx);
783
784 let active_thread_subscription =
785 cx.subscribe(&self.thread, |_, _, event, cx| match &event {
786 ActiveThreadEvent::EditingMessageTokenCountChanged => {
787 cx.notify();
788 }
789 });
790
791 self.message_editor = cx.new(|cx| {
792 MessageEditor::new(
793 self.fs.clone(),
794 self.workspace.clone(),
795 self.user_store.clone(),
796 context_store,
797 self.prompt_store.clone(),
798 self.thread_store.downgrade(),
799 self.context_store.downgrade(),
800 thread,
801 agent_panel_dock_position(cx),
802 window,
803 cx,
804 )
805 });
806 self.message_editor.focus_handle(cx).focus(window);
807
808 let message_editor_subscription =
809 cx.subscribe(&self.message_editor, |_, _, event, cx| match event {
810 MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
811 cx.notify();
812 }
813 });
814
815 self._active_thread_subscriptions = vec![
816 thread_subscription,
817 active_thread_subscription,
818 message_editor_subscription,
819 ];
820 }
821
822 fn new_prompt_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
823 let context = self
824 .context_store
825 .update(cx, |context_store, cx| context_store.create(cx));
826 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
827 .log_err()
828 .flatten();
829
830 let context_editor = cx.new(|cx| {
831 let mut editor = ContextEditor::for_context(
832 context,
833 self.fs.clone(),
834 self.workspace.clone(),
835 self.project.clone(),
836 lsp_adapter_delegate,
837 window,
838 cx,
839 );
840 editor.insert_default_prompt(window, cx);
841 editor
842 });
843
844 self.set_active_view(
845 ActiveView::prompt_editor(
846 context_editor.clone(),
847 self.language_registry.clone(),
848 window,
849 cx,
850 ),
851 window,
852 cx,
853 );
854 context_editor.focus_handle(cx).focus(window);
855 }
856
857 fn deploy_rules_library(
858 &mut self,
859 action: &OpenRulesLibrary,
860 _window: &mut Window,
861 cx: &mut Context<Self>,
862 ) {
863 open_rules_library(
864 self.language_registry.clone(),
865 Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
866 Arc::new(|| {
867 Box::new(SlashCommandCompletionProvider::new(
868 Arc::new(SlashCommandWorkingSet::default()),
869 None,
870 None,
871 ))
872 }),
873 action
874 .prompt_to_select
875 .map(|uuid| UserPromptId(uuid).into()),
876 cx,
877 )
878 .detach_and_log_err(cx);
879 }
880
881 fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
882 if matches!(self.active_view, ActiveView::History) {
883 if let Some(previous_view) = self.previous_view.take() {
884 self.set_active_view(previous_view, window, cx);
885 }
886 } else {
887 self.thread_store
888 .update(cx, |thread_store, cx| thread_store.reload(cx))
889 .detach_and_log_err(cx);
890 self.set_active_view(ActiveView::History, window, cx);
891 }
892 cx.notify();
893 }
894
895 pub(crate) fn open_saved_prompt_editor(
896 &mut self,
897 path: Arc<Path>,
898 window: &mut Window,
899 cx: &mut Context<Self>,
900 ) -> Task<Result<()>> {
901 let context = self
902 .context_store
903 .update(cx, |store, cx| store.open_local_context(path, cx));
904 cx.spawn_in(window, async move |this, cx| {
905 let context = context.await?;
906 this.update_in(cx, |this, window, cx| {
907 this.open_prompt_editor(context, window, cx);
908 })
909 })
910 }
911
912 pub(crate) fn open_prompt_editor(
913 &mut self,
914 context: Entity<AssistantContext>,
915 window: &mut Window,
916 cx: &mut Context<Self>,
917 ) {
918 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project.clone(), cx)
919 .log_err()
920 .flatten();
921 let editor = cx.new(|cx| {
922 ContextEditor::for_context(
923 context,
924 self.fs.clone(),
925 self.workspace.clone(),
926 self.project.clone(),
927 lsp_adapter_delegate,
928 window,
929 cx,
930 )
931 });
932 self.set_active_view(
933 ActiveView::prompt_editor(editor.clone(), self.language_registry.clone(), window, cx),
934 window,
935 cx,
936 );
937 }
938
939 pub(crate) fn open_thread_by_id(
940 &mut self,
941 thread_id: &ThreadId,
942 window: &mut Window,
943 cx: &mut Context<Self>,
944 ) -> Task<Result<()>> {
945 let open_thread_task = self
946 .thread_store
947 .update(cx, |this, cx| this.open_thread(thread_id, cx));
948 cx.spawn_in(window, async move |this, cx| {
949 let thread = open_thread_task.await?;
950 this.update_in(cx, |this, window, cx| {
951 this.open_thread(thread, window, cx);
952 anyhow::Ok(())
953 })??;
954 Ok(())
955 })
956 }
957
958 pub(crate) fn open_thread(
959 &mut self,
960 thread: Entity<Thread>,
961 window: &mut Window,
962 cx: &mut Context<Self>,
963 ) {
964 let thread_view = ActiveView::thread(thread.clone(), window, cx);
965 self.set_active_view(thread_view, window, cx);
966 let context_store = cx.new(|_cx| {
967 crate::context_store::ContextStore::new(
968 self.project.downgrade(),
969 Some(self.thread_store.downgrade()),
970 )
971 });
972 let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
973 if let ThreadEvent::MessageAdded(_) = &event {
974 // needed to leave empty state
975 cx.notify();
976 }
977 });
978
979 self.thread = cx.new(|cx| {
980 ActiveThread::new(
981 thread.clone(),
982 self.thread_store.clone(),
983 self.context_store.clone(),
984 context_store.clone(),
985 self.language_registry.clone(),
986 self.workspace.clone(),
987 window,
988 cx,
989 )
990 });
991 AgentDiff::set_active_thread(&self.workspace, &thread, window, cx);
992
993 let active_thread_subscription =
994 cx.subscribe(&self.thread, |_, _, event, cx| match &event {
995 ActiveThreadEvent::EditingMessageTokenCountChanged => {
996 cx.notify();
997 }
998 });
999
1000 self.message_editor = cx.new(|cx| {
1001 MessageEditor::new(
1002 self.fs.clone(),
1003 self.workspace.clone(),
1004 self.user_store.clone(),
1005 context_store,
1006 self.prompt_store.clone(),
1007 self.thread_store.downgrade(),
1008 self.context_store.downgrade(),
1009 thread,
1010 agent_panel_dock_position(cx),
1011 window,
1012 cx,
1013 )
1014 });
1015 self.message_editor.focus_handle(cx).focus(window);
1016
1017 let message_editor_subscription =
1018 cx.subscribe(&self.message_editor, |_, _, event, cx| match event {
1019 MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
1020 cx.notify();
1021 }
1022 });
1023
1024 self._active_thread_subscriptions = vec![
1025 thread_subscription,
1026 active_thread_subscription,
1027 message_editor_subscription,
1028 ];
1029 }
1030
1031 pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
1032 match self.active_view {
1033 ActiveView::Configuration | ActiveView::History => {
1034 self.active_view =
1035 ActiveView::thread(self.thread.read(cx).thread().clone(), window, cx);
1036 self.message_editor.focus_handle(cx).focus(window);
1037 cx.notify();
1038 }
1039 _ => {}
1040 }
1041 }
1042
1043 pub fn toggle_navigation_menu(
1044 &mut self,
1045 _: &ToggleNavigationMenu,
1046 window: &mut Window,
1047 cx: &mut Context<Self>,
1048 ) {
1049 self.assistant_navigation_menu_handle.toggle(window, cx);
1050 }
1051
1052 pub fn toggle_options_menu(
1053 &mut self,
1054 _: &ToggleOptionsMenu,
1055 window: &mut Window,
1056 cx: &mut Context<Self>,
1057 ) {
1058 self.assistant_dropdown_menu_handle.toggle(window, cx);
1059 }
1060
1061 pub fn increase_font_size(
1062 &mut self,
1063 action: &IncreaseBufferFontSize,
1064 _: &mut Window,
1065 cx: &mut Context<Self>,
1066 ) {
1067 self.adjust_font_size(action.persist, px(1.0), cx);
1068 }
1069
1070 pub fn decrease_font_size(
1071 &mut self,
1072 action: &DecreaseBufferFontSize,
1073 _: &mut Window,
1074 cx: &mut Context<Self>,
1075 ) {
1076 self.adjust_font_size(action.persist, px(-1.0), cx);
1077 }
1078
1079 fn adjust_font_size(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1080 if persist {
1081 update_settings_file::<ThemeSettings>(self.fs.clone(), cx, move |settings, cx| {
1082 let agent_font_size = ThemeSettings::get_global(cx).agent_font_size(cx) + delta;
1083 let _ = settings
1084 .agent_font_size
1085 .insert(theme::clamp_font_size(agent_font_size).0);
1086 });
1087 } else {
1088 theme::adjust_agent_font_size(cx, |size| {
1089 *size += delta;
1090 });
1091 }
1092 }
1093
1094 pub fn reset_font_size(
1095 &mut self,
1096 action: &ResetBufferFontSize,
1097 _: &mut Window,
1098 cx: &mut Context<Self>,
1099 ) {
1100 if action.persist {
1101 update_settings_file::<ThemeSettings>(self.fs.clone(), cx, move |settings, _| {
1102 settings.agent_font_size = None;
1103 });
1104 } else {
1105 theme::reset_agent_font_size(cx);
1106 }
1107 }
1108
1109 pub fn open_agent_diff(
1110 &mut self,
1111 _: &OpenAgentDiff,
1112 window: &mut Window,
1113 cx: &mut Context<Self>,
1114 ) {
1115 let thread = self.thread.read(cx).thread().clone();
1116 self.workspace
1117 .update(cx, |workspace, cx| {
1118 AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx)
1119 })
1120 .log_err();
1121 }
1122
1123 pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1124 let context_server_store = self.project.read(cx).context_server_store();
1125 let tools = self.thread_store.read(cx).tools();
1126 let fs = self.fs.clone();
1127
1128 self.set_active_view(ActiveView::Configuration, window, cx);
1129 self.configuration =
1130 Some(cx.new(|cx| {
1131 AssistantConfiguration::new(fs, context_server_store, tools, window, cx)
1132 }));
1133
1134 if let Some(configuration) = self.configuration.as_ref() {
1135 self.configuration_subscription = Some(cx.subscribe_in(
1136 configuration,
1137 window,
1138 Self::handle_assistant_configuration_event,
1139 ));
1140
1141 configuration.focus_handle(cx).focus(window);
1142 }
1143 }
1144
1145 pub(crate) fn open_active_thread_as_markdown(
1146 &mut self,
1147 _: &OpenActiveThreadAsMarkdown,
1148 window: &mut Window,
1149 cx: &mut Context<Self>,
1150 ) {
1151 let Some(workspace) = self
1152 .workspace
1153 .upgrade()
1154 .ok_or_else(|| anyhow!("workspace dropped"))
1155 .log_err()
1156 else {
1157 return;
1158 };
1159
1160 let Some(thread) = self.active_thread() else {
1161 return;
1162 };
1163
1164 active_thread::open_active_thread_as_markdown(thread, workspace, window, cx)
1165 .detach_and_log_err(cx);
1166 }
1167
1168 fn handle_assistant_configuration_event(
1169 &mut self,
1170 _entity: &Entity<AssistantConfiguration>,
1171 event: &AssistantConfigurationEvent,
1172 window: &mut Window,
1173 cx: &mut Context<Self>,
1174 ) {
1175 match event {
1176 AssistantConfigurationEvent::NewThread(provider) => {
1177 if LanguageModelRegistry::read_global(cx)
1178 .default_model()
1179 .map_or(true, |model| model.provider.id() != provider.id())
1180 {
1181 if let Some(model) = provider.default_model(cx) {
1182 update_settings_file::<AssistantSettings>(
1183 self.fs.clone(),
1184 cx,
1185 move |settings, _| settings.set_model(model),
1186 );
1187 }
1188 }
1189
1190 self.new_thread(&NewThread::default(), window, cx);
1191 }
1192 }
1193 }
1194
1195 pub(crate) fn active_thread(&self) -> Option<Entity<Thread>> {
1196 match &self.active_view {
1197 ActiveView::Thread { thread, .. } => thread.upgrade(),
1198 _ => None,
1199 }
1200 }
1201
1202 pub(crate) fn delete_thread(
1203 &mut self,
1204 thread_id: &ThreadId,
1205 cx: &mut Context<Self>,
1206 ) -> Task<Result<()>> {
1207 self.thread_store
1208 .update(cx, |this, cx| this.delete_thread(thread_id, cx))
1209 }
1210
1211 pub(crate) fn has_active_thread(&self) -> bool {
1212 matches!(self.active_view, ActiveView::Thread { .. })
1213 }
1214
1215 pub(crate) fn active_context_editor(&self) -> Option<Entity<ContextEditor>> {
1216 match &self.active_view {
1217 ActiveView::PromptEditor { context_editor, .. } => Some(context_editor.clone()),
1218 _ => None,
1219 }
1220 }
1221
1222 pub(crate) fn delete_context(
1223 &mut self,
1224 path: Arc<Path>,
1225 cx: &mut Context<Self>,
1226 ) -> Task<Result<()>> {
1227 self.context_store
1228 .update(cx, |this, cx| this.delete_local_context(path, cx))
1229 }
1230
1231 fn set_active_view(
1232 &mut self,
1233 new_view: ActiveView,
1234 window: &mut Window,
1235 cx: &mut Context<Self>,
1236 ) {
1237 let current_is_history = matches!(self.active_view, ActiveView::History);
1238 let new_is_history = matches!(new_view, ActiveView::History);
1239
1240 match &self.active_view {
1241 ActiveView::Thread { thread, .. } => self.history_store.update(cx, |store, cx| {
1242 if let Some(thread) = thread.upgrade() {
1243 if thread.read(cx).is_empty() {
1244 let id = thread.read(cx).id().clone();
1245 store.remove_recently_opened_thread(id, cx);
1246 }
1247 }
1248 }),
1249 _ => {}
1250 }
1251
1252 match &new_view {
1253 ActiveView::Thread { thread, .. } => self.history_store.update(cx, |store, cx| {
1254 if let Some(thread) = thread.upgrade() {
1255 let id = thread.read(cx).id().clone();
1256 store.push_recently_opened_entry(RecentEntry::Thread(id, thread), cx);
1257 }
1258 }),
1259 ActiveView::PromptEditor { context_editor, .. } => {
1260 self.history_store.update(cx, |store, cx| {
1261 let context = context_editor.read(cx).context().clone();
1262 store.push_recently_opened_entry(RecentEntry::Context(context), cx)
1263 })
1264 }
1265 _ => {}
1266 }
1267
1268 if current_is_history && !new_is_history {
1269 self.active_view = new_view;
1270 } else if !current_is_history && new_is_history {
1271 self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
1272 } else {
1273 if !new_is_history {
1274 self.previous_view = None;
1275 }
1276 self.active_view = new_view;
1277 }
1278
1279 self.focus_handle(cx).focus(window);
1280 }
1281}
1282
1283impl Focusable for AssistantPanel {
1284 fn focus_handle(&self, cx: &App) -> FocusHandle {
1285 match &self.active_view {
1286 ActiveView::Thread { .. } => self.message_editor.focus_handle(cx),
1287 ActiveView::History => self.history.focus_handle(cx),
1288 ActiveView::PromptEditor { context_editor, .. } => context_editor.focus_handle(cx),
1289 ActiveView::Configuration => {
1290 if let Some(configuration) = self.configuration.as_ref() {
1291 configuration.focus_handle(cx)
1292 } else {
1293 cx.focus_handle()
1294 }
1295 }
1296 }
1297 }
1298}
1299
1300fn agent_panel_dock_position(cx: &App) -> DockPosition {
1301 match AssistantSettings::get_global(cx).dock {
1302 AssistantDockPosition::Left => DockPosition::Left,
1303 AssistantDockPosition::Bottom => DockPosition::Bottom,
1304 AssistantDockPosition::Right => DockPosition::Right,
1305 }
1306}
1307
1308impl EventEmitter<PanelEvent> for AssistantPanel {}
1309
1310impl Panel for AssistantPanel {
1311 fn persistent_name() -> &'static str {
1312 "AgentPanel"
1313 }
1314
1315 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1316 agent_panel_dock_position(cx)
1317 }
1318
1319 fn position_is_valid(&self, position: DockPosition) -> bool {
1320 position != DockPosition::Bottom
1321 }
1322
1323 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1324 self.message_editor.update(cx, |message_editor, cx| {
1325 message_editor.set_dock_position(position, cx);
1326 });
1327
1328 settings::update_settings_file::<AssistantSettings>(
1329 self.fs.clone(),
1330 cx,
1331 move |settings, _| {
1332 let dock = match position {
1333 DockPosition::Left => AssistantDockPosition::Left,
1334 DockPosition::Bottom => AssistantDockPosition::Bottom,
1335 DockPosition::Right => AssistantDockPosition::Right,
1336 };
1337 settings.set_dock(dock);
1338 },
1339 );
1340 }
1341
1342 fn size(&self, window: &Window, cx: &App) -> Pixels {
1343 let settings = AssistantSettings::get_global(cx);
1344 match self.position(window, cx) {
1345 DockPosition::Left | DockPosition::Right => {
1346 self.width.unwrap_or(settings.default_width)
1347 }
1348 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1349 }
1350 }
1351
1352 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1353 match self.position(window, cx) {
1354 DockPosition::Left | DockPosition::Right => self.width = size,
1355 DockPosition::Bottom => self.height = size,
1356 }
1357 self.serialize(cx);
1358 cx.notify();
1359 }
1360
1361 fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
1362
1363 fn remote_id() -> Option<proto::PanelId> {
1364 Some(proto::PanelId::AssistantPanel)
1365 }
1366
1367 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1368 (self.enabled(cx) && AssistantSettings::get_global(cx).button)
1369 .then_some(IconName::ZedAssistant)
1370 }
1371
1372 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1373 Some("Agent Panel")
1374 }
1375
1376 fn toggle_action(&self) -> Box<dyn Action> {
1377 Box::new(ToggleFocus)
1378 }
1379
1380 fn activation_priority(&self) -> u32 {
1381 3
1382 }
1383
1384 fn enabled(&self, cx: &App) -> bool {
1385 AssistantSettings::get_global(cx).enabled
1386 }
1387}
1388
1389impl AssistantPanel {
1390 fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
1391 const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
1392
1393 let content = match &self.active_view {
1394 ActiveView::Thread {
1395 change_title_editor,
1396 ..
1397 } => {
1398 let active_thread = self.thread.read(cx);
1399 let is_empty = active_thread.is_empty();
1400
1401 let summary = active_thread.summary(cx);
1402
1403 if is_empty {
1404 Label::new(Thread::DEFAULT_SUMMARY.clone())
1405 .truncate()
1406 .into_any_element()
1407 } else if summary.is_none() {
1408 Label::new(LOADING_SUMMARY_PLACEHOLDER)
1409 .truncate()
1410 .into_any_element()
1411 } else {
1412 div()
1413 .w_full()
1414 .child(change_title_editor.clone())
1415 .into_any_element()
1416 }
1417 }
1418 ActiveView::PromptEditor {
1419 title_editor,
1420 context_editor,
1421 ..
1422 } => {
1423 let context_editor = context_editor.read(cx);
1424 let summary = context_editor.context().read(cx).summary();
1425
1426 match summary {
1427 None => Label::new(AssistantContext::DEFAULT_SUMMARY.clone())
1428 .truncate()
1429 .into_any_element(),
1430 Some(summary) => {
1431 if summary.done {
1432 div()
1433 .w_full()
1434 .child(title_editor.clone())
1435 .into_any_element()
1436 } else {
1437 Label::new(LOADING_SUMMARY_PLACEHOLDER)
1438 .truncate()
1439 .into_any_element()
1440 }
1441 }
1442 }
1443 }
1444 ActiveView::History => Label::new("History").truncate().into_any_element(),
1445 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
1446 };
1447
1448 h_flex()
1449 .key_context("TitleEditor")
1450 .id("TitleEditor")
1451 .flex_grow()
1452 .w_full()
1453 .max_w_full()
1454 .overflow_x_scroll()
1455 .child(content)
1456 .into_any()
1457 }
1458
1459 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1460 let active_thread = self.thread.read(cx);
1461 let user_store = self.user_store.read(cx);
1462 let thread = active_thread.thread().read(cx);
1463 let thread_id = thread.id().clone();
1464 let is_empty = active_thread.is_empty();
1465 let last_usage = active_thread.thread().read(cx).last_usage().or_else(|| {
1466 maybe!({
1467 let amount = user_store.model_request_usage_amount()?;
1468 let limit = user_store.model_request_usage_limit()?.variant?;
1469
1470 Some(RequestUsage {
1471 amount: amount as i32,
1472 limit: match limit {
1473 proto::usage_limit::Variant::Limited(limited) => {
1474 zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1475 }
1476 proto::usage_limit::Variant::Unlimited(_) => {
1477 zed_llm_client::UsageLimit::Unlimited
1478 }
1479 },
1480 })
1481 })
1482 });
1483
1484 let account_url = zed_urls::account_url(cx);
1485
1486 let show_token_count = match &self.active_view {
1487 ActiveView::Thread { .. } => !is_empty,
1488 ActiveView::PromptEditor { .. } => true,
1489 _ => false,
1490 };
1491
1492 let focus_handle = self.focus_handle(cx);
1493
1494 let go_back_button = div().child(
1495 IconButton::new("go-back", IconName::ArrowLeft)
1496 .icon_size(IconSize::Small)
1497 .on_click(cx.listener(|this, _, window, cx| {
1498 this.go_back(&workspace::GoBack, window, cx);
1499 }))
1500 .tooltip({
1501 let focus_handle = focus_handle.clone();
1502 move |window, cx| {
1503 Tooltip::for_action_in(
1504 "Go Back",
1505 &workspace::GoBack,
1506 &focus_handle,
1507 window,
1508 cx,
1509 )
1510 }
1511 }),
1512 );
1513
1514 let recent_entries_menu = div().child(
1515 PopoverMenu::new("agent-nav-menu")
1516 .trigger_with_tooltip(
1517 IconButton::new("agent-nav-menu", IconName::MenuAlt)
1518 .icon_size(IconSize::Small)
1519 .style(ui::ButtonStyle::Subtle),
1520 {
1521 let focus_handle = focus_handle.clone();
1522 move |window, cx| {
1523 Tooltip::for_action_in(
1524 "Toggle Panel Menu",
1525 &ToggleNavigationMenu,
1526 &focus_handle,
1527 window,
1528 cx,
1529 )
1530 }
1531 },
1532 )
1533 .anchor(Corner::TopLeft)
1534 .with_handle(self.assistant_navigation_menu_handle.clone())
1535 .menu({
1536 let menu = self.assistant_navigation_menu.clone();
1537 move |window, cx| {
1538 if let Some(menu) = menu.as_ref() {
1539 menu.update(cx, |_, cx| {
1540 cx.defer_in(window, |menu, window, cx| {
1541 menu.rebuild(window, cx);
1542 });
1543 })
1544 }
1545 menu.clone()
1546 }
1547 }),
1548 );
1549
1550 let agent_extra_menu = PopoverMenu::new("agent-options-menu")
1551 .trigger_with_tooltip(
1552 IconButton::new("agent-options-menu", IconName::Ellipsis)
1553 .icon_size(IconSize::Small),
1554 {
1555 let focus_handle = focus_handle.clone();
1556 move |window, cx| {
1557 Tooltip::for_action_in(
1558 "Toggle Agent Menu",
1559 &ToggleOptionsMenu,
1560 &focus_handle,
1561 window,
1562 cx,
1563 )
1564 }
1565 },
1566 )
1567 .anchor(Corner::TopRight)
1568 .with_handle(self.assistant_dropdown_menu_handle.clone())
1569 .menu(move |window, cx| {
1570 Some(ContextMenu::build(window, cx, |mut menu, _window, _cx| {
1571 menu = menu
1572 .action("New Thread", NewThread::default().boxed_clone())
1573 .action("New Text Thread", NewTextThread.boxed_clone())
1574 .when(!is_empty, |menu| {
1575 menu.action(
1576 "New From Summary",
1577 Box::new(NewThread {
1578 from_thread_id: Some(thread_id.clone()),
1579 }),
1580 )
1581 })
1582 .separator();
1583
1584 menu = menu
1585 .header("MCP Servers")
1586 .action(
1587 "View Server Extensions",
1588 Box::new(zed_actions::Extensions {
1589 category_filter: Some(
1590 zed_actions::ExtensionCategoryFilter::ContextServers,
1591 ),
1592 }),
1593 )
1594 .action("Add Custom Server…", Box::new(AddContextServer))
1595 .separator();
1596
1597 if let Some(usage) = last_usage {
1598 menu = menu
1599 .header_with_link("Prompt Usage", "Manage", account_url.clone())
1600 .custom_entry(
1601 move |_window, cx| {
1602 let used_percentage = match usage.limit {
1603 UsageLimit::Limited(limit) => {
1604 Some((usage.amount as f32 / limit as f32) * 100.)
1605 }
1606 UsageLimit::Unlimited => None,
1607 };
1608
1609 h_flex()
1610 .flex_1()
1611 .gap_1p5()
1612 .children(used_percentage.map(|percent| {
1613 ProgressBar::new("usage", percent, 100., cx)
1614 }))
1615 .child(
1616 Label::new(match usage.limit {
1617 UsageLimit::Limited(limit) => {
1618 format!("{} / {limit}", usage.amount)
1619 }
1620 UsageLimit::Unlimited => {
1621 format!("{} / ∞", usage.amount)
1622 }
1623 })
1624 .size(LabelSize::Small)
1625 .color(Color::Muted),
1626 )
1627 .into_any_element()
1628 },
1629 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
1630 )
1631 .separator()
1632 }
1633
1634 menu = menu
1635 .action("Rules…", Box::new(OpenRulesLibrary::default()))
1636 .action("Settings", Box::new(OpenConfiguration));
1637 menu
1638 }))
1639 });
1640
1641 h_flex()
1642 .id("assistant-toolbar")
1643 .h(Tab::container_height(cx))
1644 .max_w_full()
1645 .flex_none()
1646 .justify_between()
1647 .gap_2()
1648 .bg(cx.theme().colors().tab_bar_background)
1649 .border_b_1()
1650 .border_color(cx.theme().colors().border)
1651 .child(
1652 h_flex()
1653 .size_full()
1654 .pl_1()
1655 .gap_1()
1656 .child(match &self.active_view {
1657 ActiveView::History | ActiveView::Configuration => go_back_button,
1658 _ => recent_entries_menu,
1659 })
1660 .child(self.render_title_view(window, cx)),
1661 )
1662 .child(
1663 h_flex()
1664 .h_full()
1665 .gap_2()
1666 .when(show_token_count, |parent| {
1667 parent.children(self.render_token_count(&thread, cx))
1668 })
1669 .child(
1670 h_flex()
1671 .h_full()
1672 .gap(DynamicSpacing::Base02.rems(cx))
1673 .px(DynamicSpacing::Base08.rems(cx))
1674 .border_l_1()
1675 .border_color(cx.theme().colors().border)
1676 .child(
1677 IconButton::new("new", IconName::Plus)
1678 .icon_size(IconSize::Small)
1679 .style(ButtonStyle::Subtle)
1680 .tooltip(move |window, cx| {
1681 Tooltip::for_action_in(
1682 "New Thread",
1683 &NewThread::default(),
1684 &focus_handle,
1685 window,
1686 cx,
1687 )
1688 })
1689 .on_click(move |_event, window, cx| {
1690 window.dispatch_action(
1691 NewThread::default().boxed_clone(),
1692 cx,
1693 );
1694 }),
1695 )
1696 .child(agent_extra_menu),
1697 ),
1698 )
1699 }
1700
1701 fn render_token_count(&self, thread: &Thread, cx: &App) -> Option<AnyElement> {
1702 let is_generating = thread.is_generating();
1703 let message_editor = self.message_editor.read(cx);
1704
1705 let conversation_token_usage = thread.total_token_usage()?;
1706
1707 let (total_token_usage, is_estimating) = if let Some((editing_message_id, unsent_tokens)) =
1708 self.thread.read(cx).editing_message_id()
1709 {
1710 let combined = thread
1711 .token_usage_up_to_message(editing_message_id)
1712 .add(unsent_tokens);
1713
1714 (combined, unsent_tokens > 0)
1715 } else {
1716 let unsent_tokens = message_editor.last_estimated_token_count().unwrap_or(0);
1717 let combined = conversation_token_usage.add(unsent_tokens);
1718
1719 (combined, unsent_tokens > 0)
1720 };
1721
1722 let is_waiting_to_update_token_count = message_editor.is_waiting_to_update_token_count();
1723
1724 match &self.active_view {
1725 ActiveView::Thread { .. } => {
1726 if total_token_usage.total == 0 {
1727 return None;
1728 }
1729
1730 let token_color = match total_token_usage.ratio() {
1731 TokenUsageRatio::Normal if is_estimating => Color::Default,
1732 TokenUsageRatio::Normal => Color::Muted,
1733 TokenUsageRatio::Warning => Color::Warning,
1734 TokenUsageRatio::Exceeded => Color::Error,
1735 };
1736
1737 let token_count = h_flex()
1738 .id("token-count")
1739 .flex_shrink_0()
1740 .gap_0p5()
1741 .when(!is_generating && is_estimating, |parent| {
1742 parent
1743 .child(
1744 h_flex()
1745 .mr_1()
1746 .size_2p5()
1747 .justify_center()
1748 .rounded_full()
1749 .bg(cx.theme().colors().text.opacity(0.1))
1750 .child(
1751 div().size_1().rounded_full().bg(cx.theme().colors().text),
1752 ),
1753 )
1754 .tooltip(move |window, cx| {
1755 Tooltip::with_meta(
1756 "Estimated New Token Count",
1757 None,
1758 format!(
1759 "Current Conversation Tokens: {}",
1760 humanize_token_count(conversation_token_usage.total)
1761 ),
1762 window,
1763 cx,
1764 )
1765 })
1766 })
1767 .child(
1768 Label::new(humanize_token_count(total_token_usage.total))
1769 .size(LabelSize::Small)
1770 .color(token_color)
1771 .map(|label| {
1772 if is_generating || is_waiting_to_update_token_count {
1773 label
1774 .with_animation(
1775 "used-tokens-label",
1776 Animation::new(Duration::from_secs(2))
1777 .repeat()
1778 .with_easing(pulsating_between(0.6, 1.)),
1779 |label, delta| label.alpha(delta),
1780 )
1781 .into_any()
1782 } else {
1783 label.into_any_element()
1784 }
1785 }),
1786 )
1787 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1788 .child(
1789 Label::new(humanize_token_count(total_token_usage.max))
1790 .size(LabelSize::Small)
1791 .color(Color::Muted),
1792 )
1793 .into_any();
1794
1795 Some(token_count)
1796 }
1797 ActiveView::PromptEditor { context_editor, .. } => {
1798 let element = render_remaining_tokens(context_editor, cx)?;
1799
1800 Some(element.into_any_element())
1801 }
1802 _ => None,
1803 }
1804 }
1805
1806 fn should_render_upsell(&self, cx: &mut Context<Self>) -> bool {
1807 if self.hide_trial_upsell || dismissed_trial_upsell() {
1808 return false;
1809 }
1810
1811 let is_using_zed_provider = self
1812 .thread
1813 .read(cx)
1814 .thread()
1815 .read(cx)
1816 .configured_model()
1817 .map_or(false, |model| {
1818 model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
1819 });
1820 if !is_using_zed_provider {
1821 return false;
1822 }
1823
1824 let plan = self.user_store.read(cx).current_plan();
1825 if matches!(plan, Some(Plan::ZedPro | Plan::ZedProTrial)) {
1826 return false;
1827 }
1828
1829 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
1830 if has_previous_trial {
1831 return false;
1832 }
1833
1834 true
1835 }
1836
1837 fn render_trial_upsell(
1838 &self,
1839 _window: &mut Window,
1840 cx: &mut Context<Self>,
1841 ) -> Option<impl IntoElement> {
1842 if !self.should_render_upsell(cx) {
1843 return None;
1844 }
1845
1846 let checkbox = CheckboxWithLabel::new(
1847 "dont-show-again",
1848 Label::new("Don't show again").color(Color::Muted),
1849 ToggleState::Unselected,
1850 move |toggle_state, _window, cx| {
1851 let toggle_state_bool = toggle_state.selected();
1852
1853 set_trial_upsell_dismissed(toggle_state_bool, cx);
1854 },
1855 );
1856
1857 Some(
1858 div().p_2().child(
1859 v_flex()
1860 .w_full()
1861 .elevation_2(cx)
1862 .rounded(px(8.))
1863 .bg(cx.theme().colors().background.alpha(0.5))
1864 .p(px(3.))
1865
1866 .child(
1867 div()
1868 .gap_2()
1869 .flex()
1870 .flex_col()
1871 .size_full()
1872 .border_1()
1873 .rounded(px(5.))
1874 .border_color(cx.theme().colors().text.alpha(0.1))
1875 .overflow_hidden()
1876 .relative()
1877 .bg(cx.theme().colors().panel_background)
1878 .px_4()
1879 .py_3()
1880 .child(
1881 div()
1882 .absolute()
1883 .top_0()
1884 .right(px(-1.0))
1885 .w(px(441.))
1886 .h(px(167.))
1887 .child(
1888 Vector::new(VectorName::Grid, rems_from_px(441.), rems_from_px(167.)).color(ui::Color::Custom(cx.theme().colors().text.alpha(0.1)))
1889 )
1890 )
1891 .child(
1892 div()
1893 .absolute()
1894 .top(px(-8.0))
1895 .right_0()
1896 .w(px(400.))
1897 .h(px(92.))
1898 .child(
1899 Vector::new(VectorName::AiGrid, rems_from_px(400.), rems_from_px(92.)).color(ui::Color::Custom(cx.theme().colors().text.alpha(0.32)))
1900 )
1901 )
1902 // .child(
1903 // div()
1904 // .absolute()
1905 // .top_0()
1906 // .right(px(360.))
1907 // .size(px(401.))
1908 // .overflow_hidden()
1909 // .bg(cx.theme().colors().panel_background)
1910 // )
1911 .child(
1912 div()
1913 .absolute()
1914 .top_0()
1915 .right_0()
1916 .w(px(660.))
1917 .h(px(401.))
1918 .overflow_hidden()
1919 .bg(linear_gradient(
1920 75.,
1921 linear_color_stop(cx.theme().colors().panel_background.alpha(0.01), 1.0),
1922 linear_color_stop(cx.theme().colors().panel_background, 0.45),
1923 ))
1924 )
1925 .child(Headline::new("Build better with Zed Pro").size(HeadlineSize::Small))
1926 .child(Label::new("Try Zed Pro for free for 14 days - no credit card required.").size(LabelSize::Small))
1927 .child(Label::new("Use your own API keys or enable usage-based billing once you hit the cap.").color(Color::Muted))
1928 .child(
1929 h_flex()
1930 .w_full()
1931 .px_neg_1()
1932 .justify_between()
1933 .items_center()
1934 .child(h_flex().items_center().gap_1().child(checkbox))
1935 .child(
1936 h_flex()
1937 .gap_2()
1938 .child(
1939 Button::new("dismiss-button", "Not Now")
1940 .style(ButtonStyle::Transparent)
1941 .color(Color::Muted)
1942 .on_click({
1943 let assistant_panel = cx.entity();
1944 move |_, _, cx| {
1945 assistant_panel.update(
1946 cx,
1947 |this, cx| {
1948 let hidden =
1949 this.hide_trial_upsell;
1950 println!("hidden: {}", hidden);
1951 this.hide_trial_upsell = true;
1952 let new_hidden =
1953 this.hide_trial_upsell;
1954 println!(
1955 "new_hidden: {}",
1956 new_hidden
1957 );
1958
1959 cx.notify();
1960 },
1961 );
1962 }
1963 }),
1964 )
1965 .child(
1966 Button::new("cta-button", "Start Trial")
1967 .style(ButtonStyle::Transparent)
1968 .on_click(|_, _, cx| {
1969 cx.open_url(&zed_urls::account_url(cx))
1970 }),
1971 ),
1972 ),
1973 ),
1974 ),
1975 ),
1976 )
1977 }
1978
1979 fn render_active_thread_or_empty_state(
1980 &self,
1981 window: &mut Window,
1982 cx: &mut Context<Self>,
1983 ) -> AnyElement {
1984 if self.thread.read(cx).is_empty() {
1985 return self
1986 .render_thread_empty_state(window, cx)
1987 .into_any_element();
1988 }
1989
1990 self.thread.clone().into_any_element()
1991 }
1992
1993 fn configuration_error(&self, cx: &App) -> Option<ConfigurationError> {
1994 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1995 return Some(ConfigurationError::NoProvider);
1996 };
1997
1998 if !model.provider.is_authenticated(cx) {
1999 return Some(ConfigurationError::ProviderNotAuthenticated);
2000 }
2001
2002 if model.provider.must_accept_terms(cx) {
2003 return Some(ConfigurationError::ProviderPendingTermsAcceptance(
2004 model.provider,
2005 ));
2006 }
2007
2008 None
2009 }
2010
2011 fn render_thread_empty_state(
2012 &self,
2013 window: &mut Window,
2014 cx: &mut Context<Self>,
2015 ) -> impl IntoElement {
2016 let recent_history = self
2017 .history_store
2018 .update(cx, |this, cx| this.recent_entries(6, cx));
2019
2020 let configuration_error = self.configuration_error(cx);
2021 let no_error = configuration_error.is_none();
2022 let focus_handle = self.focus_handle(cx);
2023
2024 v_flex()
2025 .size_full()
2026 .when(recent_history.is_empty(), |this| {
2027 let configuration_error_ref = &configuration_error;
2028 this.child(
2029 v_flex()
2030 .size_full()
2031 .max_w_80()
2032 .mx_auto()
2033 .justify_center()
2034 .items_center()
2035 .gap_1()
2036 .child(
2037 h_flex().child(
2038 Headline::new("Welcome to the Agent Panel")
2039 ),
2040 )
2041 .when(no_error, |parent| {
2042 parent
2043 .child(
2044 h_flex().child(
2045 Label::new("Ask and build anything.")
2046 .color(Color::Muted)
2047 .mb_2p5(),
2048 ),
2049 )
2050 .child(
2051 Button::new("new-thread", "Start New Thread")
2052 .icon(IconName::Plus)
2053 .icon_position(IconPosition::Start)
2054 .icon_size(IconSize::Small)
2055 .icon_color(Color::Muted)
2056 .full_width()
2057 .key_binding(KeyBinding::for_action_in(
2058 &NewThread::default(),
2059 &focus_handle,
2060 window,
2061 cx,
2062 ))
2063 .on_click(|_event, window, cx| {
2064 window.dispatch_action(NewThread::default().boxed_clone(), cx)
2065 }),
2066 )
2067 .child(
2068 Button::new("context", "Add Context")
2069 .icon(IconName::FileCode)
2070 .icon_position(IconPosition::Start)
2071 .icon_size(IconSize::Small)
2072 .icon_color(Color::Muted)
2073 .full_width()
2074 .key_binding(KeyBinding::for_action_in(
2075 &ToggleContextPicker,
2076 &focus_handle,
2077 window,
2078 cx,
2079 ))
2080 .on_click(|_event, window, cx| {
2081 window.dispatch_action(ToggleContextPicker.boxed_clone(), cx)
2082 }),
2083 )
2084 .child(
2085 Button::new("mode", "Switch Model")
2086 .icon(IconName::DatabaseZap)
2087 .icon_position(IconPosition::Start)
2088 .icon_size(IconSize::Small)
2089 .icon_color(Color::Muted)
2090 .full_width()
2091 .key_binding(KeyBinding::for_action_in(
2092 &ToggleModelSelector,
2093 &focus_handle,
2094 window,
2095 cx,
2096 ))
2097 .on_click(|_event, window, cx| {
2098 window.dispatch_action(ToggleModelSelector.boxed_clone(), cx)
2099 }),
2100 )
2101 .child(
2102 Button::new("settings", "View Settings")
2103 .icon(IconName::Settings)
2104 .icon_position(IconPosition::Start)
2105 .icon_size(IconSize::Small)
2106 .icon_color(Color::Muted)
2107 .full_width()
2108 .key_binding(KeyBinding::for_action_in(
2109 &OpenConfiguration,
2110 &focus_handle,
2111 window,
2112 cx,
2113 ))
2114 .on_click(|_event, window, cx| {
2115 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
2116 }),
2117 )
2118 })
2119 .map(|parent| {
2120 match configuration_error_ref {
2121 Some(ConfigurationError::ProviderNotAuthenticated)
2122 | Some(ConfigurationError::NoProvider) => {
2123 parent
2124 .child(
2125 h_flex().child(
2126 Label::new("To start using the agent, configure at least one LLM provider.")
2127 .color(Color::Muted)
2128 .mb_2p5()
2129 )
2130 )
2131 .child(
2132 Button::new("settings", "Configure a Provider")
2133 .icon(IconName::Settings)
2134 .icon_position(IconPosition::Start)
2135 .icon_size(IconSize::Small)
2136 .icon_color(Color::Muted)
2137 .full_width()
2138 .key_binding(KeyBinding::for_action_in(
2139 &OpenConfiguration,
2140 &focus_handle,
2141 window,
2142 cx,
2143 ))
2144 .on_click(|_event, window, cx| {
2145 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
2146 }),
2147 )
2148 }
2149 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2150 parent.children(
2151 provider.render_accept_terms(
2152 LanguageModelProviderTosView::ThreadFreshStart,
2153 cx,
2154 ),
2155 )
2156 }
2157 None => parent,
2158 }
2159 })
2160 )
2161 })
2162 .when(!recent_history.is_empty(), |parent| {
2163 let focus_handle = focus_handle.clone();
2164 let configuration_error_ref = &configuration_error;
2165
2166 parent
2167 .overflow_hidden()
2168 .p_1p5()
2169 .justify_end()
2170 .gap_1()
2171 .child(
2172 h_flex()
2173 .pl_1p5()
2174 .pb_1()
2175 .w_full()
2176 .justify_between()
2177 .border_b_1()
2178 .border_color(cx.theme().colors().border_variant)
2179 .child(
2180 Label::new("Past Interactions")
2181 .size(LabelSize::Small)
2182 .color(Color::Muted),
2183 )
2184 .child(
2185 Button::new("view-history", "View All")
2186 .style(ButtonStyle::Subtle)
2187 .label_size(LabelSize::Small)
2188 .key_binding(
2189 KeyBinding::for_action_in(
2190 &OpenHistory,
2191 &self.focus_handle(cx),
2192 window,
2193 cx,
2194 ).map(|kb| kb.size(rems_from_px(12.))),
2195 )
2196 .on_click(move |_event, window, cx| {
2197 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2198 }),
2199 ),
2200 )
2201 .child(
2202 v_flex()
2203 .gap_1()
2204 .children(
2205 recent_history.into_iter().map(|entry| {
2206 // TODO: Add keyboard navigation.
2207 match entry {
2208 HistoryEntry::Thread(thread) => {
2209 PastThread::new(thread, cx.entity().downgrade(), false, vec![], EntryTimeFormat::DateAndTime)
2210 .into_any_element()
2211 }
2212 HistoryEntry::Context(context) => {
2213 PastContext::new(context, cx.entity().downgrade(), false, vec![], EntryTimeFormat::DateAndTime)
2214 .into_any_element()
2215 }
2216 }
2217 }),
2218 )
2219 )
2220 .map(|parent| {
2221 match configuration_error_ref {
2222 Some(ConfigurationError::ProviderNotAuthenticated)
2223 | Some(ConfigurationError::NoProvider) => {
2224 parent
2225 .child(
2226 Banner::new()
2227 .severity(ui::Severity::Warning)
2228 .child(
2229 Label::new(
2230 "Configure at least one LLM provider to start using the panel.",
2231 )
2232 .size(LabelSize::Small),
2233 )
2234 .action_slot(
2235 Button::new("settings", "Configure Provider")
2236 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2237 .label_size(LabelSize::Small)
2238 .key_binding(
2239 KeyBinding::for_action_in(
2240 &OpenConfiguration,
2241 &focus_handle,
2242 window,
2243 cx,
2244 )
2245 .map(|kb| kb.size(rems_from_px(12.))),
2246 )
2247 .on_click(|_event, window, cx| {
2248 window.dispatch_action(
2249 OpenConfiguration.boxed_clone(),
2250 cx,
2251 )
2252 }),
2253 ),
2254 )
2255 }
2256 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2257 parent
2258 .child(
2259 Banner::new()
2260 .severity(ui::Severity::Warning)
2261 .child(
2262 h_flex()
2263 .w_full()
2264 .children(
2265 provider.render_accept_terms(
2266 LanguageModelProviderTosView::ThreadtEmptyState,
2267 cx,
2268 ),
2269 ),
2270 ),
2271 )
2272 }
2273 None => parent,
2274 }
2275 })
2276 })
2277 }
2278
2279 fn render_tool_use_limit_reached(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2280 let tool_use_limit_reached = self
2281 .thread
2282 .read(cx)
2283 .thread()
2284 .read(cx)
2285 .tool_use_limit_reached();
2286 if !tool_use_limit_reached {
2287 return None;
2288 }
2289
2290 let model = self
2291 .thread
2292 .read(cx)
2293 .thread()
2294 .read(cx)
2295 .configured_model()?
2296 .model;
2297
2298 let max_mode_upsell = if model.supports_max_mode() {
2299 " Enable max mode for unlimited tool use."
2300 } else {
2301 ""
2302 };
2303
2304 Some(
2305 Banner::new()
2306 .severity(ui::Severity::Info)
2307 .child(h_flex().child(Label::new(format!(
2308 "Consecutive tool use limit reached.{max_mode_upsell}"
2309 ))))
2310 .into_any_element(),
2311 )
2312 }
2313
2314 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2315 let last_error = self.thread.read(cx).last_error()?;
2316
2317 Some(
2318 div()
2319 .absolute()
2320 .right_3()
2321 .bottom_12()
2322 .max_w_96()
2323 .py_2()
2324 .px_3()
2325 .elevation_2(cx)
2326 .occlude()
2327 .child(match last_error {
2328 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
2329 ThreadError::MaxMonthlySpendReached => {
2330 self.render_max_monthly_spend_reached_error(cx)
2331 }
2332 ThreadError::ModelRequestLimitReached { plan } => {
2333 self.render_model_request_limit_reached_error(plan, cx)
2334 }
2335 ThreadError::Message { header, message } => {
2336 self.render_error_message(header, message, cx)
2337 }
2338 })
2339 .into_any(),
2340 )
2341 }
2342
2343 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2344 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.";
2345
2346 v_flex()
2347 .gap_0p5()
2348 .child(
2349 h_flex()
2350 .gap_1p5()
2351 .items_center()
2352 .child(Icon::new(IconName::XCircle).color(Color::Error))
2353 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2354 )
2355 .child(
2356 div()
2357 .id("error-message")
2358 .max_h_24()
2359 .overflow_y_scroll()
2360 .child(Label::new(ERROR_MESSAGE)),
2361 )
2362 .child(
2363 h_flex()
2364 .justify_end()
2365 .mt_1()
2366 .gap_1()
2367 .child(self.create_copy_button(ERROR_MESSAGE))
2368 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2369 |this, _, _, cx| {
2370 this.thread.update(cx, |this, _cx| {
2371 this.clear_last_error();
2372 });
2373
2374 cx.open_url(&zed_urls::account_url(cx));
2375 cx.notify();
2376 },
2377 )))
2378 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2379 |this, _, _, cx| {
2380 this.thread.update(cx, |this, _cx| {
2381 this.clear_last_error();
2382 });
2383
2384 cx.notify();
2385 },
2386 ))),
2387 )
2388 .into_any()
2389 }
2390
2391 fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
2392 const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
2393
2394 v_flex()
2395 .gap_0p5()
2396 .child(
2397 h_flex()
2398 .gap_1p5()
2399 .items_center()
2400 .child(Icon::new(IconName::XCircle).color(Color::Error))
2401 .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
2402 )
2403 .child(
2404 div()
2405 .id("error-message")
2406 .max_h_24()
2407 .overflow_y_scroll()
2408 .child(Label::new(ERROR_MESSAGE)),
2409 )
2410 .child(
2411 h_flex()
2412 .justify_end()
2413 .mt_1()
2414 .gap_1()
2415 .child(self.create_copy_button(ERROR_MESSAGE))
2416 .child(
2417 Button::new("subscribe", "Update Monthly Spend Limit").on_click(
2418 cx.listener(|this, _, _, cx| {
2419 this.thread.update(cx, |this, _cx| {
2420 this.clear_last_error();
2421 });
2422
2423 cx.open_url(&zed_urls::account_url(cx));
2424 cx.notify();
2425 }),
2426 ),
2427 )
2428 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2429 |this, _, _, cx| {
2430 this.thread.update(cx, |this, _cx| {
2431 this.clear_last_error();
2432 });
2433
2434 cx.notify();
2435 },
2436 ))),
2437 )
2438 .into_any()
2439 }
2440
2441 fn render_model_request_limit_reached_error(
2442 &self,
2443 plan: Plan,
2444 cx: &mut Context<Self>,
2445 ) -> AnyElement {
2446 let error_message = match plan {
2447 Plan::ZedPro => {
2448 "Model request limit reached. Upgrade to usage-based billing for more requests."
2449 }
2450 Plan::ZedProTrial => {
2451 "Model request limit reached. Upgrade to Zed Pro for more requests."
2452 }
2453 Plan::Free => "Model request limit reached. Upgrade to Zed Pro for more requests.",
2454 };
2455 let call_to_action = match plan {
2456 Plan::ZedPro => "Upgrade to usage-based billing",
2457 Plan::ZedProTrial => "Upgrade to Zed Pro",
2458 Plan::Free => "Upgrade to Zed Pro",
2459 };
2460
2461 v_flex()
2462 .gap_0p5()
2463 .child(
2464 h_flex()
2465 .gap_1p5()
2466 .items_center()
2467 .child(Icon::new(IconName::XCircle).color(Color::Error))
2468 .child(Label::new("Model Request Limit Reached").weight(FontWeight::MEDIUM)),
2469 )
2470 .child(
2471 div()
2472 .id("error-message")
2473 .max_h_24()
2474 .overflow_y_scroll()
2475 .child(Label::new(error_message)),
2476 )
2477 .child(
2478 h_flex()
2479 .justify_end()
2480 .mt_1()
2481 .gap_1()
2482 .child(self.create_copy_button(error_message))
2483 .child(
2484 Button::new("subscribe", call_to_action).on_click(cx.listener(
2485 |this, _, _, cx| {
2486 this.thread.update(cx, |this, _cx| {
2487 this.clear_last_error();
2488 });
2489
2490 cx.open_url(&zed_urls::account_url(cx));
2491 cx.notify();
2492 },
2493 )),
2494 )
2495 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2496 |this, _, _, cx| {
2497 this.thread.update(cx, |this, _cx| {
2498 this.clear_last_error();
2499 });
2500
2501 cx.notify();
2502 },
2503 ))),
2504 )
2505 .into_any()
2506 }
2507
2508 fn render_error_message(
2509 &self,
2510 header: SharedString,
2511 message: SharedString,
2512 cx: &mut Context<Self>,
2513 ) -> AnyElement {
2514 let message_with_header = format!("{}\n{}", header, message);
2515 v_flex()
2516 .gap_0p5()
2517 .child(
2518 h_flex()
2519 .gap_1p5()
2520 .items_center()
2521 .child(Icon::new(IconName::XCircle).color(Color::Error))
2522 .child(Label::new(header).weight(FontWeight::MEDIUM)),
2523 )
2524 .child(
2525 div()
2526 .id("error-message")
2527 .max_h_32()
2528 .overflow_y_scroll()
2529 .child(Label::new(message.clone())),
2530 )
2531 .child(
2532 h_flex()
2533 .justify_end()
2534 .mt_1()
2535 .gap_1()
2536 .child(self.create_copy_button(message_with_header))
2537 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2538 |this, _, _, cx| {
2539 this.thread.update(cx, |this, _cx| {
2540 this.clear_last_error();
2541 });
2542
2543 cx.notify();
2544 },
2545 ))),
2546 )
2547 .into_any()
2548 }
2549
2550 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
2551 let is_local = self.project.read(cx).is_local();
2552 div()
2553 .invisible()
2554 .absolute()
2555 .top_0()
2556 .right_0()
2557 .bottom_0()
2558 .left_0()
2559 .bg(cx.theme().colors().drop_target_background)
2560 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
2561 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
2562 .when(is_local, |this| {
2563 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
2564 })
2565 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
2566 let item = tab.pane.read(cx).item_for_index(tab.ix);
2567 let project_paths = item
2568 .and_then(|item| item.project_path(cx))
2569 .into_iter()
2570 .collect::<Vec<_>>();
2571 this.handle_drop(project_paths, vec![], window, cx);
2572 }))
2573 .on_drop(
2574 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2575 let project_paths = selection
2576 .items()
2577 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
2578 .collect::<Vec<_>>();
2579 this.handle_drop(project_paths, vec![], window, cx);
2580 }),
2581 )
2582 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
2583 let tasks = paths
2584 .paths()
2585 .into_iter()
2586 .map(|path| {
2587 Workspace::project_path_for_path(this.project.clone(), &path, false, cx)
2588 })
2589 .collect::<Vec<_>>();
2590 cx.spawn_in(window, async move |this, cx| {
2591 let mut paths = vec![];
2592 let mut added_worktrees = vec![];
2593 let opened_paths = futures::future::join_all(tasks).await;
2594 for entry in opened_paths {
2595 if let Some((worktree, project_path)) = entry.log_err() {
2596 added_worktrees.push(worktree);
2597 paths.push(project_path);
2598 }
2599 }
2600 this.update_in(cx, |this, window, cx| {
2601 this.handle_drop(paths, added_worktrees, window, cx);
2602 })
2603 .ok();
2604 })
2605 .detach();
2606 }))
2607 }
2608
2609 fn handle_drop(
2610 &mut self,
2611 paths: Vec<ProjectPath>,
2612 added_worktrees: Vec<Entity<Worktree>>,
2613 window: &mut Window,
2614 cx: &mut Context<Self>,
2615 ) {
2616 match &self.active_view {
2617 ActiveView::Thread { .. } => {
2618 let context_store = self.thread.read(cx).context_store().clone();
2619 context_store.update(cx, move |context_store, cx| {
2620 let mut tasks = Vec::new();
2621 for project_path in &paths {
2622 tasks.push(context_store.add_file_from_path(
2623 project_path.clone(),
2624 false,
2625 cx,
2626 ));
2627 }
2628 cx.background_spawn(async move {
2629 futures::future::join_all(tasks).await;
2630 // Need to hold onto the worktrees until they have already been used when
2631 // opening the buffers.
2632 drop(added_worktrees);
2633 })
2634 .detach();
2635 });
2636 }
2637 ActiveView::PromptEditor { context_editor, .. } => {
2638 context_editor.update(cx, |context_editor, cx| {
2639 ContextEditor::insert_dragged_files(
2640 context_editor,
2641 paths,
2642 added_worktrees,
2643 window,
2644 cx,
2645 );
2646 });
2647 }
2648 ActiveView::History | ActiveView::Configuration => {}
2649 }
2650 }
2651
2652 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
2653 let message = message.into();
2654 IconButton::new("copy", IconName::Copy)
2655 .on_click(move |_, _, cx| {
2656 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
2657 })
2658 .tooltip(Tooltip::text("Copy Error Message"))
2659 }
2660
2661 fn key_context(&self) -> KeyContext {
2662 let mut key_context = KeyContext::new_with_defaults();
2663 key_context.add("AgentPanel");
2664 if matches!(self.active_view, ActiveView::PromptEditor { .. }) {
2665 key_context.add("prompt_editor");
2666 }
2667 key_context
2668 }
2669}
2670
2671impl Render for AssistantPanel {
2672 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2673 v_flex()
2674 .key_context(self.key_context())
2675 .justify_between()
2676 .size_full()
2677 .on_action(cx.listener(Self::cancel))
2678 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
2679 this.new_thread(action, window, cx);
2680 }))
2681 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
2682 this.open_history(window, cx);
2683 }))
2684 .on_action(cx.listener(|this, _: &OpenConfiguration, window, cx| {
2685 this.open_configuration(window, cx);
2686 }))
2687 .on_action(cx.listener(Self::open_active_thread_as_markdown))
2688 .on_action(cx.listener(Self::deploy_rules_library))
2689 .on_action(cx.listener(Self::open_agent_diff))
2690 .on_action(cx.listener(Self::go_back))
2691 .on_action(cx.listener(Self::toggle_navigation_menu))
2692 .on_action(cx.listener(Self::toggle_options_menu))
2693 .on_action(cx.listener(Self::increase_font_size))
2694 .on_action(cx.listener(Self::decrease_font_size))
2695 .on_action(cx.listener(Self::reset_font_size))
2696 .child(self.render_toolbar(window, cx))
2697 .children(self.render_trial_upsell(window, cx))
2698 .map(|parent| match &self.active_view {
2699 ActiveView::Thread { .. } => parent.child(
2700 v_flex()
2701 .relative()
2702 .justify_between()
2703 .size_full()
2704 .child(self.render_active_thread_or_empty_state(window, cx))
2705 .children(self.render_tool_use_limit_reached(cx))
2706 .child(h_flex().child(self.message_editor.clone()))
2707 .children(self.render_last_error(cx))
2708 .child(self.render_drag_target(cx)),
2709 ),
2710 ActiveView::History => parent.child(self.history.clone()),
2711 ActiveView::PromptEditor {
2712 context_editor,
2713 buffer_search_bar,
2714 ..
2715 } => {
2716 let mut registrar = buffer_search::DivRegistrar::new(
2717 |this, _, _cx| match &this.active_view {
2718 ActiveView::PromptEditor {
2719 buffer_search_bar, ..
2720 } => Some(buffer_search_bar.clone()),
2721 _ => None,
2722 },
2723 cx,
2724 );
2725 BufferSearchBar::register(&mut registrar);
2726 parent.child(
2727 registrar
2728 .into_div()
2729 .size_full()
2730 .relative()
2731 .map(|parent| {
2732 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
2733 if buffer_search_bar.is_dismissed() {
2734 return parent;
2735 }
2736 parent.child(
2737 div()
2738 .p(DynamicSpacing::Base08.rems(cx))
2739 .border_b_1()
2740 .border_color(cx.theme().colors().border_variant)
2741 .bg(cx.theme().colors().editor_background)
2742 .child(buffer_search_bar.render(window, cx)),
2743 )
2744 })
2745 })
2746 .child(context_editor.clone())
2747 .child(self.render_drag_target(cx)),
2748 )
2749 }
2750 ActiveView::Configuration => parent.children(self.configuration.clone()),
2751 })
2752 }
2753}
2754
2755struct PromptLibraryInlineAssist {
2756 workspace: WeakEntity<Workspace>,
2757}
2758
2759impl PromptLibraryInlineAssist {
2760 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
2761 Self { workspace }
2762 }
2763}
2764
2765impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
2766 fn assist(
2767 &self,
2768 prompt_editor: &Entity<Editor>,
2769 initial_prompt: Option<String>,
2770 window: &mut Window,
2771 cx: &mut Context<RulesLibrary>,
2772 ) {
2773 InlineAssistant::update_global(cx, |assistant, cx| {
2774 let Some(project) = self
2775 .workspace
2776 .upgrade()
2777 .map(|workspace| workspace.read(cx).project().downgrade())
2778 else {
2779 return;
2780 };
2781 let prompt_store = None;
2782 let thread_store = None;
2783 let text_thread_store = None;
2784 let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
2785 assistant.assist(
2786 &prompt_editor,
2787 self.workspace.clone(),
2788 context_store,
2789 project,
2790 prompt_store,
2791 thread_store,
2792 text_thread_store,
2793 initial_prompt,
2794 window,
2795 cx,
2796 )
2797 })
2798 }
2799
2800 fn focus_assistant_panel(
2801 &self,
2802 workspace: &mut Workspace,
2803 window: &mut Window,
2804 cx: &mut Context<Workspace>,
2805 ) -> bool {
2806 workspace
2807 .focus_panel::<AssistantPanel>(window, cx)
2808 .is_some()
2809 }
2810}
2811
2812pub struct ConcreteAssistantPanelDelegate;
2813
2814impl AssistantPanelDelegate for ConcreteAssistantPanelDelegate {
2815 fn active_context_editor(
2816 &self,
2817 workspace: &mut Workspace,
2818 _window: &mut Window,
2819 cx: &mut Context<Workspace>,
2820 ) -> Option<Entity<ContextEditor>> {
2821 let panel = workspace.panel::<AssistantPanel>(cx)?;
2822 panel.read(cx).active_context_editor()
2823 }
2824
2825 fn open_saved_context(
2826 &self,
2827 workspace: &mut Workspace,
2828 path: Arc<Path>,
2829 window: &mut Window,
2830 cx: &mut Context<Workspace>,
2831 ) -> Task<Result<()>> {
2832 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2833 return Task::ready(Err(anyhow!("Agent panel not found")));
2834 };
2835
2836 panel.update(cx, |panel, cx| {
2837 panel.open_saved_prompt_editor(path, window, cx)
2838 })
2839 }
2840
2841 fn open_remote_context(
2842 &self,
2843 _workspace: &mut Workspace,
2844 _context_id: assistant_context_editor::ContextId,
2845 _window: &mut Window,
2846 _cx: &mut Context<Workspace>,
2847 ) -> Task<Result<Entity<ContextEditor>>> {
2848 Task::ready(Err(anyhow!("opening remote context not implemented")))
2849 }
2850
2851 fn quote_selection(
2852 &self,
2853 workspace: &mut Workspace,
2854 selection_ranges: Vec<Range<Anchor>>,
2855 buffer: Entity<MultiBuffer>,
2856 window: &mut Window,
2857 cx: &mut Context<Workspace>,
2858 ) {
2859 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2860 return;
2861 };
2862
2863 if !panel.focus_handle(cx).contains_focused(window, cx) {
2864 workspace.toggle_panel_focus::<AssistantPanel>(window, cx);
2865 }
2866
2867 panel.update(cx, |_, cx| {
2868 // Wait to create a new context until the workspace is no longer
2869 // being updated.
2870 cx.defer_in(window, move |panel, window, cx| {
2871 if panel.has_active_thread() {
2872 panel.message_editor.update(cx, |message_editor, cx| {
2873 message_editor.context_store().update(cx, |store, cx| {
2874 let buffer = buffer.read(cx);
2875 let selection_ranges = selection_ranges
2876 .into_iter()
2877 .flat_map(|range| {
2878 let (start_buffer, start) =
2879 buffer.text_anchor_for_position(range.start, cx)?;
2880 let (end_buffer, end) =
2881 buffer.text_anchor_for_position(range.end, cx)?;
2882 if start_buffer != end_buffer {
2883 return None;
2884 }
2885 Some((start_buffer, start..end))
2886 })
2887 .collect::<Vec<_>>();
2888
2889 for (buffer, range) in selection_ranges {
2890 store.add_selection(buffer, range, cx);
2891 }
2892 })
2893 })
2894 } else if let Some(context_editor) = panel.active_context_editor() {
2895 let snapshot = buffer.read(cx).snapshot(cx);
2896 let selection_ranges = selection_ranges
2897 .into_iter()
2898 .map(|range| range.to_point(&snapshot))
2899 .collect::<Vec<_>>();
2900
2901 context_editor.update(cx, |context_editor, cx| {
2902 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
2903 });
2904 }
2905 });
2906 });
2907 }
2908}
2909
2910const DISMISSED_TRIAL_UPSELL_KEY: &str = "dismissed-trial-upsell";
2911
2912fn dismissed_trial_upsell() -> bool {
2913 db::kvp::KEY_VALUE_STORE
2914 .read_kvp(DISMISSED_TRIAL_UPSELL_KEY)
2915 .log_err()
2916 .map_or(false, |s| s.is_some())
2917}
2918
2919fn set_trial_upsell_dismissed(is_dismissed: bool, cx: &mut App) {
2920 db::write_and_log(cx, move || async move {
2921 if is_dismissed {
2922 db::kvp::KEY_VALUE_STORE
2923 .write_kvp(DISMISSED_TRIAL_UPSELL_KEY.into(), "1".into())
2924 .await
2925 } else {
2926 db::kvp::KEY_VALUE_STORE
2927 .delete_kvp(DISMISSED_TRIAL_UPSELL_KEY.into())
2928 .await
2929 }
2930 })
2931}