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