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 editor_empty = self.message_editor.read(cx).is_editor_fully_empty(cx);
1466 let last_usage = active_thread.thread().read(cx).last_usage().or_else(|| {
1467 maybe!({
1468 let amount = user_store.model_request_usage_amount()?;
1469 let limit = user_store.model_request_usage_limit()?.variant?;
1470
1471 Some(RequestUsage {
1472 amount: amount as i32,
1473 limit: match limit {
1474 proto::usage_limit::Variant::Limited(limited) => {
1475 zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1476 }
1477 proto::usage_limit::Variant::Unlimited(_) => {
1478 zed_llm_client::UsageLimit::Unlimited
1479 }
1480 },
1481 })
1482 })
1483 });
1484
1485 let account_url = zed_urls::account_url(cx);
1486
1487 let show_token_count = match &self.active_view {
1488 ActiveView::Thread { .. } => !is_empty || !editor_empty,
1489 ActiveView::PromptEditor { .. } => true,
1490 _ => false,
1491 };
1492
1493 let focus_handle = self.focus_handle(cx);
1494
1495 let go_back_button = div().child(
1496 IconButton::new("go-back", IconName::ArrowLeft)
1497 .icon_size(IconSize::Small)
1498 .on_click(cx.listener(|this, _, window, cx| {
1499 this.go_back(&workspace::GoBack, window, cx);
1500 }))
1501 .tooltip({
1502 let focus_handle = focus_handle.clone();
1503 move |window, cx| {
1504 Tooltip::for_action_in(
1505 "Go Back",
1506 &workspace::GoBack,
1507 &focus_handle,
1508 window,
1509 cx,
1510 )
1511 }
1512 }),
1513 );
1514
1515 let recent_entries_menu = div().child(
1516 PopoverMenu::new("agent-nav-menu")
1517 .trigger_with_tooltip(
1518 IconButton::new("agent-nav-menu", IconName::MenuAlt)
1519 .icon_size(IconSize::Small)
1520 .style(ui::ButtonStyle::Subtle),
1521 {
1522 let focus_handle = focus_handle.clone();
1523 move |window, cx| {
1524 Tooltip::for_action_in(
1525 "Toggle Panel Menu",
1526 &ToggleNavigationMenu,
1527 &focus_handle,
1528 window,
1529 cx,
1530 )
1531 }
1532 },
1533 )
1534 .anchor(Corner::TopLeft)
1535 .with_handle(self.assistant_navigation_menu_handle.clone())
1536 .menu({
1537 let menu = self.assistant_navigation_menu.clone();
1538 move |window, cx| {
1539 if let Some(menu) = menu.as_ref() {
1540 menu.update(cx, |_, cx| {
1541 cx.defer_in(window, |menu, window, cx| {
1542 menu.rebuild(window, cx);
1543 });
1544 })
1545 }
1546 menu.clone()
1547 }
1548 }),
1549 );
1550
1551 let agent_extra_menu = PopoverMenu::new("agent-options-menu")
1552 .trigger_with_tooltip(
1553 IconButton::new("agent-options-menu", IconName::Ellipsis)
1554 .icon_size(IconSize::Small),
1555 {
1556 let focus_handle = focus_handle.clone();
1557 move |window, cx| {
1558 Tooltip::for_action_in(
1559 "Toggle Agent Menu",
1560 &ToggleOptionsMenu,
1561 &focus_handle,
1562 window,
1563 cx,
1564 )
1565 }
1566 },
1567 )
1568 .anchor(Corner::TopRight)
1569 .with_handle(self.assistant_dropdown_menu_handle.clone())
1570 .menu(move |window, cx| {
1571 Some(ContextMenu::build(window, cx, |mut menu, _window, _cx| {
1572 menu = menu
1573 .action("New Thread", NewThread::default().boxed_clone())
1574 .action("New Text Thread", NewTextThread.boxed_clone())
1575 .when(!is_empty, |menu| {
1576 menu.action(
1577 "New From Summary",
1578 Box::new(NewThread {
1579 from_thread_id: Some(thread_id.clone()),
1580 }),
1581 )
1582 })
1583 .separator();
1584
1585 menu = menu
1586 .header("MCP Servers")
1587 .action(
1588 "View Server Extensions",
1589 Box::new(zed_actions::Extensions {
1590 category_filter: Some(
1591 zed_actions::ExtensionCategoryFilter::ContextServers,
1592 ),
1593 }),
1594 )
1595 .action("Add Custom Server…", Box::new(AddContextServer))
1596 .separator();
1597
1598 if let Some(usage) = last_usage {
1599 menu = menu
1600 .header_with_link("Prompt Usage", "Manage", account_url.clone())
1601 .custom_entry(
1602 move |_window, cx| {
1603 let used_percentage = match usage.limit {
1604 UsageLimit::Limited(limit) => {
1605 Some((usage.amount as f32 / limit as f32) * 100.)
1606 }
1607 UsageLimit::Unlimited => None,
1608 };
1609
1610 h_flex()
1611 .flex_1()
1612 .gap_1p5()
1613 .children(used_percentage.map(|percent| {
1614 ProgressBar::new("usage", percent, 100., cx)
1615 }))
1616 .child(
1617 Label::new(match usage.limit {
1618 UsageLimit::Limited(limit) => {
1619 format!("{} / {limit}", usage.amount)
1620 }
1621 UsageLimit::Unlimited => {
1622 format!("{} / ∞", usage.amount)
1623 }
1624 })
1625 .size(LabelSize::Small)
1626 .color(Color::Muted),
1627 )
1628 .into_any_element()
1629 },
1630 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
1631 )
1632 .separator()
1633 }
1634
1635 menu = menu
1636 .action("Rules…", Box::new(OpenRulesLibrary::default()))
1637 .action("Settings", Box::new(OpenConfiguration));
1638 menu
1639 }))
1640 });
1641
1642 h_flex()
1643 .id("assistant-toolbar")
1644 .h(Tab::container_height(cx))
1645 .max_w_full()
1646 .flex_none()
1647 .justify_between()
1648 .gap_2()
1649 .bg(cx.theme().colors().tab_bar_background)
1650 .border_b_1()
1651 .border_color(cx.theme().colors().border)
1652 .child(
1653 h_flex()
1654 .size_full()
1655 .pl_1()
1656 .gap_1()
1657 .child(match &self.active_view {
1658 ActiveView::History | ActiveView::Configuration => go_back_button,
1659 _ => recent_entries_menu,
1660 })
1661 .child(self.render_title_view(window, cx)),
1662 )
1663 .child(
1664 h_flex()
1665 .h_full()
1666 .gap_2()
1667 .when(show_token_count, |parent| {
1668 parent.children(self.render_token_count(&thread, cx))
1669 })
1670 .child(
1671 h_flex()
1672 .h_full()
1673 .gap(DynamicSpacing::Base02.rems(cx))
1674 .px(DynamicSpacing::Base08.rems(cx))
1675 .border_l_1()
1676 .border_color(cx.theme().colors().border)
1677 .child(
1678 IconButton::new("new", IconName::Plus)
1679 .icon_size(IconSize::Small)
1680 .style(ButtonStyle::Subtle)
1681 .tooltip(move |window, cx| {
1682 Tooltip::for_action_in(
1683 "New Thread",
1684 &NewThread::default(),
1685 &focus_handle,
1686 window,
1687 cx,
1688 )
1689 })
1690 .on_click(move |_event, window, cx| {
1691 window.dispatch_action(
1692 NewThread::default().boxed_clone(),
1693 cx,
1694 );
1695 }),
1696 )
1697 .child(agent_extra_menu),
1698 ),
1699 )
1700 }
1701
1702 fn render_token_count(&self, thread: &Thread, cx: &App) -> Option<AnyElement> {
1703 let is_generating = thread.is_generating();
1704 let message_editor = self.message_editor.read(cx);
1705
1706 let conversation_token_usage = thread.total_token_usage()?;
1707
1708 let (total_token_usage, is_estimating) = if let Some((editing_message_id, unsent_tokens)) =
1709 self.thread.read(cx).editing_message_id()
1710 {
1711 let combined = thread
1712 .token_usage_up_to_message(editing_message_id)
1713 .add(unsent_tokens);
1714
1715 (combined, unsent_tokens > 0)
1716 } else {
1717 let unsent_tokens = message_editor.last_estimated_token_count().unwrap_or(0);
1718 let combined = conversation_token_usage.add(unsent_tokens);
1719
1720 (combined, unsent_tokens > 0)
1721 };
1722
1723 let is_waiting_to_update_token_count = message_editor.is_waiting_to_update_token_count();
1724
1725 match &self.active_view {
1726 ActiveView::Thread { .. } => {
1727 if total_token_usage.total == 0 {
1728 return None;
1729 }
1730
1731 let token_color = match total_token_usage.ratio() {
1732 TokenUsageRatio::Normal if is_estimating => Color::Default,
1733 TokenUsageRatio::Normal => Color::Muted,
1734 TokenUsageRatio::Warning => Color::Warning,
1735 TokenUsageRatio::Exceeded => Color::Error,
1736 };
1737
1738 let token_count = h_flex()
1739 .id("token-count")
1740 .flex_shrink_0()
1741 .gap_0p5()
1742 .when(!is_generating && is_estimating, |parent| {
1743 parent
1744 .child(
1745 h_flex()
1746 .mr_1()
1747 .size_2p5()
1748 .justify_center()
1749 .rounded_full()
1750 .bg(cx.theme().colors().text.opacity(0.1))
1751 .child(
1752 div().size_1().rounded_full().bg(cx.theme().colors().text),
1753 ),
1754 )
1755 .tooltip(move |window, cx| {
1756 Tooltip::with_meta(
1757 "Estimated New Token Count",
1758 None,
1759 format!(
1760 "Current Conversation Tokens: {}",
1761 humanize_token_count(conversation_token_usage.total)
1762 ),
1763 window,
1764 cx,
1765 )
1766 })
1767 })
1768 .child(
1769 Label::new(humanize_token_count(total_token_usage.total))
1770 .size(LabelSize::Small)
1771 .color(token_color)
1772 .map(|label| {
1773 if is_generating || is_waiting_to_update_token_count {
1774 label
1775 .with_animation(
1776 "used-tokens-label",
1777 Animation::new(Duration::from_secs(2))
1778 .repeat()
1779 .with_easing(pulsating_between(0.6, 1.)),
1780 |label, delta| label.alpha(delta),
1781 )
1782 .into_any()
1783 } else {
1784 label.into_any_element()
1785 }
1786 }),
1787 )
1788 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1789 .child(
1790 Label::new(humanize_token_count(total_token_usage.max))
1791 .size(LabelSize::Small)
1792 .color(Color::Muted),
1793 )
1794 .into_any();
1795
1796 Some(token_count)
1797 }
1798 ActiveView::PromptEditor { context_editor, .. } => {
1799 let element = render_remaining_tokens(context_editor, cx)?;
1800
1801 Some(element.into_any_element())
1802 }
1803 _ => None,
1804 }
1805 }
1806
1807 fn should_render_upsell(&self, cx: &mut Context<Self>) -> bool {
1808 if self.hide_trial_upsell || dismissed_trial_upsell() {
1809 return false;
1810 }
1811
1812 let is_using_zed_provider = self
1813 .thread
1814 .read(cx)
1815 .thread()
1816 .read(cx)
1817 .configured_model()
1818 .map_or(false, |model| {
1819 model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
1820 });
1821 if !is_using_zed_provider {
1822 return false;
1823 }
1824
1825 let plan = self.user_store.read(cx).current_plan();
1826 if matches!(plan, Some(Plan::ZedPro | Plan::ZedProTrial)) {
1827 return false;
1828 }
1829
1830 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
1831 if has_previous_trial {
1832 return false;
1833 }
1834
1835 true
1836 }
1837
1838 fn render_trial_upsell(
1839 &self,
1840 _window: &mut Window,
1841 cx: &mut Context<Self>,
1842 ) -> Option<impl IntoElement> {
1843 if !self.should_render_upsell(cx) {
1844 return None;
1845 }
1846
1847 let checkbox = CheckboxWithLabel::new(
1848 "dont-show-again",
1849 Label::new("Don't show again").color(Color::Muted),
1850 ToggleState::Unselected,
1851 move |toggle_state, _window, cx| {
1852 let toggle_state_bool = toggle_state.selected();
1853
1854 set_trial_upsell_dismissed(toggle_state_bool, cx);
1855 },
1856 );
1857
1858 Some(
1859 div().p_2().child(
1860 v_flex()
1861 .w_full()
1862 .elevation_2(cx)
1863 .rounded(px(8.))
1864 .bg(cx.theme().colors().background.alpha(0.5))
1865 .p(px(3.))
1866
1867 .child(
1868 div()
1869 .gap_2()
1870 .flex()
1871 .flex_col()
1872 .size_full()
1873 .border_1()
1874 .rounded(px(5.))
1875 .border_color(cx.theme().colors().text.alpha(0.1))
1876 .overflow_hidden()
1877 .relative()
1878 .bg(cx.theme().colors().panel_background)
1879 .px_4()
1880 .py_3()
1881 .child(
1882 div()
1883 .absolute()
1884 .top_0()
1885 .right(px(-1.0))
1886 .w(px(441.))
1887 .h(px(167.))
1888 .child(
1889 Vector::new(VectorName::Grid, rems_from_px(441.), rems_from_px(167.)).color(ui::Color::Custom(cx.theme().colors().text.alpha(0.1)))
1890 )
1891 )
1892 .child(
1893 div()
1894 .absolute()
1895 .top(px(-8.0))
1896 .right_0()
1897 .w(px(400.))
1898 .h(px(92.))
1899 .child(
1900 Vector::new(VectorName::AiGrid, rems_from_px(400.), rems_from_px(92.)).color(ui::Color::Custom(cx.theme().colors().text.alpha(0.32)))
1901 )
1902 )
1903 // .child(
1904 // div()
1905 // .absolute()
1906 // .top_0()
1907 // .right(px(360.))
1908 // .size(px(401.))
1909 // .overflow_hidden()
1910 // .bg(cx.theme().colors().panel_background)
1911 // )
1912 .child(
1913 div()
1914 .absolute()
1915 .top_0()
1916 .right_0()
1917 .w(px(660.))
1918 .h(px(401.))
1919 .overflow_hidden()
1920 .bg(linear_gradient(
1921 75.,
1922 linear_color_stop(cx.theme().colors().panel_background.alpha(0.01), 1.0),
1923 linear_color_stop(cx.theme().colors().panel_background, 0.45),
1924 ))
1925 )
1926 .child(Headline::new("Build better with Zed Pro").size(HeadlineSize::Small))
1927 .child(Label::new("Try Zed Pro for free for 14 days - no credit card required.").size(LabelSize::Small))
1928 .child(Label::new("Use your own API keys or enable usage-based billing once you hit the cap.").color(Color::Muted))
1929 .child(
1930 h_flex()
1931 .w_full()
1932 .px_neg_1()
1933 .justify_between()
1934 .items_center()
1935 .child(h_flex().items_center().gap_1().child(checkbox))
1936 .child(
1937 h_flex()
1938 .gap_2()
1939 .child(
1940 Button::new("dismiss-button", "Not Now")
1941 .style(ButtonStyle::Transparent)
1942 .color(Color::Muted)
1943 .on_click({
1944 let assistant_panel = cx.entity();
1945 move |_, _, cx| {
1946 assistant_panel.update(
1947 cx,
1948 |this, cx| {
1949 let hidden =
1950 this.hide_trial_upsell;
1951 println!("hidden: {}", hidden);
1952 this.hide_trial_upsell = true;
1953 let new_hidden =
1954 this.hide_trial_upsell;
1955 println!(
1956 "new_hidden: {}",
1957 new_hidden
1958 );
1959
1960 cx.notify();
1961 },
1962 );
1963 }
1964 }),
1965 )
1966 .child(
1967 Button::new("cta-button", "Start Trial")
1968 .style(ButtonStyle::Transparent)
1969 .on_click(|_, _, cx| {
1970 cx.open_url(&zed_urls::account_url(cx))
1971 }),
1972 ),
1973 ),
1974 ),
1975 ),
1976 ),
1977 )
1978 }
1979
1980 fn render_active_thread_or_empty_state(
1981 &self,
1982 window: &mut Window,
1983 cx: &mut Context<Self>,
1984 ) -> AnyElement {
1985 if self.thread.read(cx).is_empty() {
1986 return self
1987 .render_thread_empty_state(window, cx)
1988 .into_any_element();
1989 }
1990
1991 self.thread.clone().into_any_element()
1992 }
1993
1994 fn configuration_error(&self, cx: &App) -> Option<ConfigurationError> {
1995 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1996 return Some(ConfigurationError::NoProvider);
1997 };
1998
1999 if !model.provider.is_authenticated(cx) {
2000 return Some(ConfigurationError::ProviderNotAuthenticated);
2001 }
2002
2003 if model.provider.must_accept_terms(cx) {
2004 return Some(ConfigurationError::ProviderPendingTermsAcceptance(
2005 model.provider,
2006 ));
2007 }
2008
2009 None
2010 }
2011
2012 fn render_thread_empty_state(
2013 &self,
2014 window: &mut Window,
2015 cx: &mut Context<Self>,
2016 ) -> impl IntoElement {
2017 let recent_history = self
2018 .history_store
2019 .update(cx, |this, cx| this.recent_entries(6, cx));
2020
2021 let configuration_error = self.configuration_error(cx);
2022 let no_error = configuration_error.is_none();
2023 let focus_handle = self.focus_handle(cx);
2024
2025 v_flex()
2026 .size_full()
2027 .when(recent_history.is_empty(), |this| {
2028 let configuration_error_ref = &configuration_error;
2029 this.child(
2030 v_flex()
2031 .size_full()
2032 .max_w_80()
2033 .mx_auto()
2034 .justify_center()
2035 .items_center()
2036 .gap_1()
2037 .child(
2038 h_flex().child(
2039 Headline::new("Welcome to the Agent Panel")
2040 ),
2041 )
2042 .when(no_error, |parent| {
2043 parent
2044 .child(
2045 h_flex().child(
2046 Label::new("Ask and build anything.")
2047 .color(Color::Muted)
2048 .mb_2p5(),
2049 ),
2050 )
2051 .child(
2052 Button::new("new-thread", "Start New Thread")
2053 .icon(IconName::Plus)
2054 .icon_position(IconPosition::Start)
2055 .icon_size(IconSize::Small)
2056 .icon_color(Color::Muted)
2057 .full_width()
2058 .key_binding(KeyBinding::for_action_in(
2059 &NewThread::default(),
2060 &focus_handle,
2061 window,
2062 cx,
2063 ))
2064 .on_click(|_event, window, cx| {
2065 window.dispatch_action(NewThread::default().boxed_clone(), cx)
2066 }),
2067 )
2068 .child(
2069 Button::new("context", "Add Context")
2070 .icon(IconName::FileCode)
2071 .icon_position(IconPosition::Start)
2072 .icon_size(IconSize::Small)
2073 .icon_color(Color::Muted)
2074 .full_width()
2075 .key_binding(KeyBinding::for_action_in(
2076 &ToggleContextPicker,
2077 &focus_handle,
2078 window,
2079 cx,
2080 ))
2081 .on_click(|_event, window, cx| {
2082 window.dispatch_action(ToggleContextPicker.boxed_clone(), cx)
2083 }),
2084 )
2085 .child(
2086 Button::new("mode", "Switch Model")
2087 .icon(IconName::DatabaseZap)
2088 .icon_position(IconPosition::Start)
2089 .icon_size(IconSize::Small)
2090 .icon_color(Color::Muted)
2091 .full_width()
2092 .key_binding(KeyBinding::for_action_in(
2093 &ToggleModelSelector,
2094 &focus_handle,
2095 window,
2096 cx,
2097 ))
2098 .on_click(|_event, window, cx| {
2099 window.dispatch_action(ToggleModelSelector.boxed_clone(), cx)
2100 }),
2101 )
2102 .child(
2103 Button::new("settings", "View Settings")
2104 .icon(IconName::Settings)
2105 .icon_position(IconPosition::Start)
2106 .icon_size(IconSize::Small)
2107 .icon_color(Color::Muted)
2108 .full_width()
2109 .key_binding(KeyBinding::for_action_in(
2110 &OpenConfiguration,
2111 &focus_handle,
2112 window,
2113 cx,
2114 ))
2115 .on_click(|_event, window, cx| {
2116 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
2117 }),
2118 )
2119 })
2120 .map(|parent| {
2121 match configuration_error_ref {
2122 Some(ConfigurationError::ProviderNotAuthenticated)
2123 | Some(ConfigurationError::NoProvider) => {
2124 parent
2125 .child(
2126 h_flex().child(
2127 Label::new("To start using the agent, configure at least one LLM provider.")
2128 .color(Color::Muted)
2129 .mb_2p5()
2130 )
2131 )
2132 .child(
2133 Button::new("settings", "Configure a Provider")
2134 .icon(IconName::Settings)
2135 .icon_position(IconPosition::Start)
2136 .icon_size(IconSize::Small)
2137 .icon_color(Color::Muted)
2138 .full_width()
2139 .key_binding(KeyBinding::for_action_in(
2140 &OpenConfiguration,
2141 &focus_handle,
2142 window,
2143 cx,
2144 ))
2145 .on_click(|_event, window, cx| {
2146 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
2147 }),
2148 )
2149 }
2150 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2151 parent.children(
2152 provider.render_accept_terms(
2153 LanguageModelProviderTosView::ThreadFreshStart,
2154 cx,
2155 ),
2156 )
2157 }
2158 None => parent,
2159 }
2160 })
2161 )
2162 })
2163 .when(!recent_history.is_empty(), |parent| {
2164 let focus_handle = focus_handle.clone();
2165 let configuration_error_ref = &configuration_error;
2166
2167 parent
2168 .overflow_hidden()
2169 .p_1p5()
2170 .justify_end()
2171 .gap_1()
2172 .child(
2173 h_flex()
2174 .pl_1p5()
2175 .pb_1()
2176 .w_full()
2177 .justify_between()
2178 .border_b_1()
2179 .border_color(cx.theme().colors().border_variant)
2180 .child(
2181 Label::new("Past Interactions")
2182 .size(LabelSize::Small)
2183 .color(Color::Muted),
2184 )
2185 .child(
2186 Button::new("view-history", "View All")
2187 .style(ButtonStyle::Subtle)
2188 .label_size(LabelSize::Small)
2189 .key_binding(
2190 KeyBinding::for_action_in(
2191 &OpenHistory,
2192 &self.focus_handle(cx),
2193 window,
2194 cx,
2195 ).map(|kb| kb.size(rems_from_px(12.))),
2196 )
2197 .on_click(move |_event, window, cx| {
2198 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2199 }),
2200 ),
2201 )
2202 .child(
2203 v_flex()
2204 .gap_1()
2205 .children(
2206 recent_history.into_iter().map(|entry| {
2207 // TODO: Add keyboard navigation.
2208 match entry {
2209 HistoryEntry::Thread(thread) => {
2210 PastThread::new(thread, cx.entity().downgrade(), false, vec![], EntryTimeFormat::DateAndTime)
2211 .into_any_element()
2212 }
2213 HistoryEntry::Context(context) => {
2214 PastContext::new(context, cx.entity().downgrade(), false, vec![], EntryTimeFormat::DateAndTime)
2215 .into_any_element()
2216 }
2217 }
2218 }),
2219 )
2220 )
2221 .map(|parent| {
2222 match configuration_error_ref {
2223 Some(ConfigurationError::ProviderNotAuthenticated)
2224 | Some(ConfigurationError::NoProvider) => {
2225 parent
2226 .child(
2227 Banner::new()
2228 .severity(ui::Severity::Warning)
2229 .child(
2230 Label::new(
2231 "Configure at least one LLM provider to start using the panel.",
2232 )
2233 .size(LabelSize::Small),
2234 )
2235 .action_slot(
2236 Button::new("settings", "Configure Provider")
2237 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2238 .label_size(LabelSize::Small)
2239 .key_binding(
2240 KeyBinding::for_action_in(
2241 &OpenConfiguration,
2242 &focus_handle,
2243 window,
2244 cx,
2245 )
2246 .map(|kb| kb.size(rems_from_px(12.))),
2247 )
2248 .on_click(|_event, window, cx| {
2249 window.dispatch_action(
2250 OpenConfiguration.boxed_clone(),
2251 cx,
2252 )
2253 }),
2254 ),
2255 )
2256 }
2257 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2258 parent
2259 .child(
2260 Banner::new()
2261 .severity(ui::Severity::Warning)
2262 .child(
2263 h_flex()
2264 .w_full()
2265 .children(
2266 provider.render_accept_terms(
2267 LanguageModelProviderTosView::ThreadtEmptyState,
2268 cx,
2269 ),
2270 ),
2271 ),
2272 )
2273 }
2274 None => parent,
2275 }
2276 })
2277 })
2278 }
2279
2280 fn render_tool_use_limit_reached(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2281 let tool_use_limit_reached = self
2282 .thread
2283 .read(cx)
2284 .thread()
2285 .read(cx)
2286 .tool_use_limit_reached();
2287 if !tool_use_limit_reached {
2288 return None;
2289 }
2290
2291 let model = self
2292 .thread
2293 .read(cx)
2294 .thread()
2295 .read(cx)
2296 .configured_model()?
2297 .model;
2298
2299 let max_mode_upsell = if model.supports_max_mode() {
2300 " Enable max mode for unlimited tool use."
2301 } else {
2302 ""
2303 };
2304
2305 Some(
2306 Banner::new()
2307 .severity(ui::Severity::Info)
2308 .child(h_flex().child(Label::new(format!(
2309 "Consecutive tool use limit reached.{max_mode_upsell}"
2310 ))))
2311 .into_any_element(),
2312 )
2313 }
2314
2315 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2316 let last_error = self.thread.read(cx).last_error()?;
2317
2318 Some(
2319 div()
2320 .absolute()
2321 .right_3()
2322 .bottom_12()
2323 .max_w_96()
2324 .py_2()
2325 .px_3()
2326 .elevation_2(cx)
2327 .occlude()
2328 .child(match last_error {
2329 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
2330 ThreadError::MaxMonthlySpendReached => {
2331 self.render_max_monthly_spend_reached_error(cx)
2332 }
2333 ThreadError::ModelRequestLimitReached { plan } => {
2334 self.render_model_request_limit_reached_error(plan, cx)
2335 }
2336 ThreadError::Message { header, message } => {
2337 self.render_error_message(header, message, cx)
2338 }
2339 })
2340 .into_any(),
2341 )
2342 }
2343
2344 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2345 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.";
2346
2347 v_flex()
2348 .gap_0p5()
2349 .child(
2350 h_flex()
2351 .gap_1p5()
2352 .items_center()
2353 .child(Icon::new(IconName::XCircle).color(Color::Error))
2354 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2355 )
2356 .child(
2357 div()
2358 .id("error-message")
2359 .max_h_24()
2360 .overflow_y_scroll()
2361 .child(Label::new(ERROR_MESSAGE)),
2362 )
2363 .child(
2364 h_flex()
2365 .justify_end()
2366 .mt_1()
2367 .gap_1()
2368 .child(self.create_copy_button(ERROR_MESSAGE))
2369 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2370 |this, _, _, cx| {
2371 this.thread.update(cx, |this, _cx| {
2372 this.clear_last_error();
2373 });
2374
2375 cx.open_url(&zed_urls::account_url(cx));
2376 cx.notify();
2377 },
2378 )))
2379 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2380 |this, _, _, cx| {
2381 this.thread.update(cx, |this, _cx| {
2382 this.clear_last_error();
2383 });
2384
2385 cx.notify();
2386 },
2387 ))),
2388 )
2389 .into_any()
2390 }
2391
2392 fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
2393 const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
2394
2395 v_flex()
2396 .gap_0p5()
2397 .child(
2398 h_flex()
2399 .gap_1p5()
2400 .items_center()
2401 .child(Icon::new(IconName::XCircle).color(Color::Error))
2402 .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
2403 )
2404 .child(
2405 div()
2406 .id("error-message")
2407 .max_h_24()
2408 .overflow_y_scroll()
2409 .child(Label::new(ERROR_MESSAGE)),
2410 )
2411 .child(
2412 h_flex()
2413 .justify_end()
2414 .mt_1()
2415 .gap_1()
2416 .child(self.create_copy_button(ERROR_MESSAGE))
2417 .child(
2418 Button::new("subscribe", "Update Monthly Spend Limit").on_click(
2419 cx.listener(|this, _, _, cx| {
2420 this.thread.update(cx, |this, _cx| {
2421 this.clear_last_error();
2422 });
2423
2424 cx.open_url(&zed_urls::account_url(cx));
2425 cx.notify();
2426 }),
2427 ),
2428 )
2429 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2430 |this, _, _, cx| {
2431 this.thread.update(cx, |this, _cx| {
2432 this.clear_last_error();
2433 });
2434
2435 cx.notify();
2436 },
2437 ))),
2438 )
2439 .into_any()
2440 }
2441
2442 fn render_model_request_limit_reached_error(
2443 &self,
2444 plan: Plan,
2445 cx: &mut Context<Self>,
2446 ) -> AnyElement {
2447 let error_message = match plan {
2448 Plan::ZedPro => {
2449 "Model request limit reached. Upgrade to usage-based billing for more requests."
2450 }
2451 Plan::ZedProTrial => {
2452 "Model request limit reached. Upgrade to Zed Pro for more requests."
2453 }
2454 Plan::Free => "Model request limit reached. Upgrade to Zed Pro for more requests.",
2455 };
2456 let call_to_action = match plan {
2457 Plan::ZedPro => "Upgrade to usage-based billing",
2458 Plan::ZedProTrial => "Upgrade to Zed Pro",
2459 Plan::Free => "Upgrade to Zed Pro",
2460 };
2461
2462 v_flex()
2463 .gap_0p5()
2464 .child(
2465 h_flex()
2466 .gap_1p5()
2467 .items_center()
2468 .child(Icon::new(IconName::XCircle).color(Color::Error))
2469 .child(Label::new("Model Request Limit Reached").weight(FontWeight::MEDIUM)),
2470 )
2471 .child(
2472 div()
2473 .id("error-message")
2474 .max_h_24()
2475 .overflow_y_scroll()
2476 .child(Label::new(error_message)),
2477 )
2478 .child(
2479 h_flex()
2480 .justify_end()
2481 .mt_1()
2482 .gap_1()
2483 .child(self.create_copy_button(error_message))
2484 .child(
2485 Button::new("subscribe", call_to_action).on_click(cx.listener(
2486 |this, _, _, cx| {
2487 this.thread.update(cx, |this, _cx| {
2488 this.clear_last_error();
2489 });
2490
2491 cx.open_url(&zed_urls::account_url(cx));
2492 cx.notify();
2493 },
2494 )),
2495 )
2496 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2497 |this, _, _, cx| {
2498 this.thread.update(cx, |this, _cx| {
2499 this.clear_last_error();
2500 });
2501
2502 cx.notify();
2503 },
2504 ))),
2505 )
2506 .into_any()
2507 }
2508
2509 fn render_error_message(
2510 &self,
2511 header: SharedString,
2512 message: SharedString,
2513 cx: &mut Context<Self>,
2514 ) -> AnyElement {
2515 let message_with_header = format!("{}\n{}", header, message);
2516 v_flex()
2517 .gap_0p5()
2518 .child(
2519 h_flex()
2520 .gap_1p5()
2521 .items_center()
2522 .child(Icon::new(IconName::XCircle).color(Color::Error))
2523 .child(Label::new(header).weight(FontWeight::MEDIUM)),
2524 )
2525 .child(
2526 div()
2527 .id("error-message")
2528 .max_h_32()
2529 .overflow_y_scroll()
2530 .child(Label::new(message.clone())),
2531 )
2532 .child(
2533 h_flex()
2534 .justify_end()
2535 .mt_1()
2536 .gap_1()
2537 .child(self.create_copy_button(message_with_header))
2538 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2539 |this, _, _, cx| {
2540 this.thread.update(cx, |this, _cx| {
2541 this.clear_last_error();
2542 });
2543
2544 cx.notify();
2545 },
2546 ))),
2547 )
2548 .into_any()
2549 }
2550
2551 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
2552 let is_local = self.project.read(cx).is_local();
2553 div()
2554 .invisible()
2555 .absolute()
2556 .top_0()
2557 .right_0()
2558 .bottom_0()
2559 .left_0()
2560 .bg(cx.theme().colors().drop_target_background)
2561 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
2562 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
2563 .when(is_local, |this| {
2564 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
2565 })
2566 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
2567 let item = tab.pane.read(cx).item_for_index(tab.ix);
2568 let project_paths = item
2569 .and_then(|item| item.project_path(cx))
2570 .into_iter()
2571 .collect::<Vec<_>>();
2572 this.handle_drop(project_paths, vec![], window, cx);
2573 }))
2574 .on_drop(
2575 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2576 let project_paths = selection
2577 .items()
2578 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
2579 .collect::<Vec<_>>();
2580 this.handle_drop(project_paths, vec![], window, cx);
2581 }),
2582 )
2583 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
2584 let tasks = paths
2585 .paths()
2586 .into_iter()
2587 .map(|path| {
2588 Workspace::project_path_for_path(this.project.clone(), &path, false, cx)
2589 })
2590 .collect::<Vec<_>>();
2591 cx.spawn_in(window, async move |this, cx| {
2592 let mut paths = vec![];
2593 let mut added_worktrees = vec![];
2594 let opened_paths = futures::future::join_all(tasks).await;
2595 for entry in opened_paths {
2596 if let Some((worktree, project_path)) = entry.log_err() {
2597 added_worktrees.push(worktree);
2598 paths.push(project_path);
2599 }
2600 }
2601 this.update_in(cx, |this, window, cx| {
2602 this.handle_drop(paths, added_worktrees, window, cx);
2603 })
2604 .ok();
2605 })
2606 .detach();
2607 }))
2608 }
2609
2610 fn handle_drop(
2611 &mut self,
2612 paths: Vec<ProjectPath>,
2613 added_worktrees: Vec<Entity<Worktree>>,
2614 window: &mut Window,
2615 cx: &mut Context<Self>,
2616 ) {
2617 match &self.active_view {
2618 ActiveView::Thread { .. } => {
2619 let context_store = self.thread.read(cx).context_store().clone();
2620 context_store.update(cx, move |context_store, cx| {
2621 let mut tasks = Vec::new();
2622 for project_path in &paths {
2623 tasks.push(context_store.add_file_from_path(
2624 project_path.clone(),
2625 false,
2626 cx,
2627 ));
2628 }
2629 cx.background_spawn(async move {
2630 futures::future::join_all(tasks).await;
2631 // Need to hold onto the worktrees until they have already been used when
2632 // opening the buffers.
2633 drop(added_worktrees);
2634 })
2635 .detach();
2636 });
2637 }
2638 ActiveView::PromptEditor { context_editor, .. } => {
2639 context_editor.update(cx, |context_editor, cx| {
2640 ContextEditor::insert_dragged_files(
2641 context_editor,
2642 paths,
2643 added_worktrees,
2644 window,
2645 cx,
2646 );
2647 });
2648 }
2649 ActiveView::History | ActiveView::Configuration => {}
2650 }
2651 }
2652
2653 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
2654 let message = message.into();
2655 IconButton::new("copy", IconName::Copy)
2656 .on_click(move |_, _, cx| {
2657 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
2658 })
2659 .tooltip(Tooltip::text("Copy Error Message"))
2660 }
2661
2662 fn key_context(&self) -> KeyContext {
2663 let mut key_context = KeyContext::new_with_defaults();
2664 key_context.add("AgentPanel");
2665 if matches!(self.active_view, ActiveView::PromptEditor { .. }) {
2666 key_context.add("prompt_editor");
2667 }
2668 key_context
2669 }
2670}
2671
2672impl Render for AssistantPanel {
2673 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2674 v_flex()
2675 .key_context(self.key_context())
2676 .justify_between()
2677 .size_full()
2678 .on_action(cx.listener(Self::cancel))
2679 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
2680 this.new_thread(action, window, cx);
2681 }))
2682 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
2683 this.open_history(window, cx);
2684 }))
2685 .on_action(cx.listener(|this, _: &OpenConfiguration, window, cx| {
2686 this.open_configuration(window, cx);
2687 }))
2688 .on_action(cx.listener(Self::open_active_thread_as_markdown))
2689 .on_action(cx.listener(Self::deploy_rules_library))
2690 .on_action(cx.listener(Self::open_agent_diff))
2691 .on_action(cx.listener(Self::go_back))
2692 .on_action(cx.listener(Self::toggle_navigation_menu))
2693 .on_action(cx.listener(Self::toggle_options_menu))
2694 .on_action(cx.listener(Self::increase_font_size))
2695 .on_action(cx.listener(Self::decrease_font_size))
2696 .on_action(cx.listener(Self::reset_font_size))
2697 .child(self.render_toolbar(window, cx))
2698 .children(self.render_trial_upsell(window, cx))
2699 .map(|parent| match &self.active_view {
2700 ActiveView::Thread { .. } => parent.child(
2701 v_flex()
2702 .relative()
2703 .justify_between()
2704 .size_full()
2705 .child(self.render_active_thread_or_empty_state(window, cx))
2706 .children(self.render_tool_use_limit_reached(cx))
2707 .child(h_flex().child(self.message_editor.clone()))
2708 .children(self.render_last_error(cx))
2709 .child(self.render_drag_target(cx)),
2710 ),
2711 ActiveView::History => parent.child(self.history.clone()),
2712 ActiveView::PromptEditor {
2713 context_editor,
2714 buffer_search_bar,
2715 ..
2716 } => {
2717 let mut registrar = buffer_search::DivRegistrar::new(
2718 |this, _, _cx| match &this.active_view {
2719 ActiveView::PromptEditor {
2720 buffer_search_bar, ..
2721 } => Some(buffer_search_bar.clone()),
2722 _ => None,
2723 },
2724 cx,
2725 );
2726 BufferSearchBar::register(&mut registrar);
2727 parent.child(
2728 registrar
2729 .into_div()
2730 .size_full()
2731 .relative()
2732 .map(|parent| {
2733 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
2734 if buffer_search_bar.is_dismissed() {
2735 return parent;
2736 }
2737 parent.child(
2738 div()
2739 .p(DynamicSpacing::Base08.rems(cx))
2740 .border_b_1()
2741 .border_color(cx.theme().colors().border_variant)
2742 .bg(cx.theme().colors().editor_background)
2743 .child(buffer_search_bar.render(window, cx)),
2744 )
2745 })
2746 })
2747 .child(context_editor.clone())
2748 .child(self.render_drag_target(cx)),
2749 )
2750 }
2751 ActiveView::Configuration => parent.children(self.configuration.clone()),
2752 })
2753 }
2754}
2755
2756struct PromptLibraryInlineAssist {
2757 workspace: WeakEntity<Workspace>,
2758}
2759
2760impl PromptLibraryInlineAssist {
2761 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
2762 Self { workspace }
2763 }
2764}
2765
2766impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
2767 fn assist(
2768 &self,
2769 prompt_editor: &Entity<Editor>,
2770 initial_prompt: Option<String>,
2771 window: &mut Window,
2772 cx: &mut Context<RulesLibrary>,
2773 ) {
2774 InlineAssistant::update_global(cx, |assistant, cx| {
2775 let Some(project) = self
2776 .workspace
2777 .upgrade()
2778 .map(|workspace| workspace.read(cx).project().downgrade())
2779 else {
2780 return;
2781 };
2782 let prompt_store = None;
2783 let thread_store = None;
2784 let text_thread_store = None;
2785 let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
2786 assistant.assist(
2787 &prompt_editor,
2788 self.workspace.clone(),
2789 context_store,
2790 project,
2791 prompt_store,
2792 thread_store,
2793 text_thread_store,
2794 initial_prompt,
2795 window,
2796 cx,
2797 )
2798 })
2799 }
2800
2801 fn focus_assistant_panel(
2802 &self,
2803 workspace: &mut Workspace,
2804 window: &mut Window,
2805 cx: &mut Context<Workspace>,
2806 ) -> bool {
2807 workspace
2808 .focus_panel::<AssistantPanel>(window, cx)
2809 .is_some()
2810 }
2811}
2812
2813pub struct ConcreteAssistantPanelDelegate;
2814
2815impl AssistantPanelDelegate for ConcreteAssistantPanelDelegate {
2816 fn active_context_editor(
2817 &self,
2818 workspace: &mut Workspace,
2819 _window: &mut Window,
2820 cx: &mut Context<Workspace>,
2821 ) -> Option<Entity<ContextEditor>> {
2822 let panel = workspace.panel::<AssistantPanel>(cx)?;
2823 panel.read(cx).active_context_editor()
2824 }
2825
2826 fn open_saved_context(
2827 &self,
2828 workspace: &mut Workspace,
2829 path: Arc<Path>,
2830 window: &mut Window,
2831 cx: &mut Context<Workspace>,
2832 ) -> Task<Result<()>> {
2833 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2834 return Task::ready(Err(anyhow!("Agent panel not found")));
2835 };
2836
2837 panel.update(cx, |panel, cx| {
2838 panel.open_saved_prompt_editor(path, window, cx)
2839 })
2840 }
2841
2842 fn open_remote_context(
2843 &self,
2844 _workspace: &mut Workspace,
2845 _context_id: assistant_context_editor::ContextId,
2846 _window: &mut Window,
2847 _cx: &mut Context<Workspace>,
2848 ) -> Task<Result<Entity<ContextEditor>>> {
2849 Task::ready(Err(anyhow!("opening remote context not implemented")))
2850 }
2851
2852 fn quote_selection(
2853 &self,
2854 workspace: &mut Workspace,
2855 selection_ranges: Vec<Range<Anchor>>,
2856 buffer: Entity<MultiBuffer>,
2857 window: &mut Window,
2858 cx: &mut Context<Workspace>,
2859 ) {
2860 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2861 return;
2862 };
2863
2864 if !panel.focus_handle(cx).contains_focused(window, cx) {
2865 workspace.toggle_panel_focus::<AssistantPanel>(window, cx);
2866 }
2867
2868 panel.update(cx, |_, cx| {
2869 // Wait to create a new context until the workspace is no longer
2870 // being updated.
2871 cx.defer_in(window, move |panel, window, cx| {
2872 if panel.has_active_thread() {
2873 panel.message_editor.update(cx, |message_editor, cx| {
2874 message_editor.context_store().update(cx, |store, cx| {
2875 let buffer = buffer.read(cx);
2876 let selection_ranges = selection_ranges
2877 .into_iter()
2878 .flat_map(|range| {
2879 let (start_buffer, start) =
2880 buffer.text_anchor_for_position(range.start, cx)?;
2881 let (end_buffer, end) =
2882 buffer.text_anchor_for_position(range.end, cx)?;
2883 if start_buffer != end_buffer {
2884 return None;
2885 }
2886 Some((start_buffer, start..end))
2887 })
2888 .collect::<Vec<_>>();
2889
2890 for (buffer, range) in selection_ranges {
2891 store.add_selection(buffer, range, cx);
2892 }
2893 })
2894 })
2895 } else if let Some(context_editor) = panel.active_context_editor() {
2896 let snapshot = buffer.read(cx).snapshot(cx);
2897 let selection_ranges = selection_ranges
2898 .into_iter()
2899 .map(|range| range.to_point(&snapshot))
2900 .collect::<Vec<_>>();
2901
2902 context_editor.update(cx, |context_editor, cx| {
2903 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
2904 });
2905 }
2906 });
2907 });
2908 }
2909}
2910
2911const DISMISSED_TRIAL_UPSELL_KEY: &str = "dismissed-trial-upsell";
2912
2913fn dismissed_trial_upsell() -> bool {
2914 db::kvp::KEY_VALUE_STORE
2915 .read_kvp(DISMISSED_TRIAL_UPSELL_KEY)
2916 .log_err()
2917 .map_or(false, |s| s.is_some())
2918}
2919
2920fn set_trial_upsell_dismissed(is_dismissed: bool, cx: &mut App) {
2921 db::write_and_log(cx, move || async move {
2922 if is_dismissed {
2923 db::kvp::KEY_VALUE_STORE
2924 .write_kvp(DISMISSED_TRIAL_UPSELL_KEY.into(), "1".into())
2925 .await
2926 } else {
2927 db::kvp::KEY_VALUE_STORE
2928 .delete_kvp(DISMISSED_TRIAL_UPSELL_KEY.into())
2929 .await
2930 }
2931 })
2932}