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, ToggleBurnMode, ToggleContextPicker,
71 ToggleNavigationMenu, 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 TextThread {
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::TextThread { .. } => 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::TextThread {
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 if let Some(previous_view) = self.previous_view.take() {
1088 self.active_view = previous_view;
1089
1090 match &self.active_view {
1091 ActiveView::Thread { .. } => {
1092 self.message_editor.focus_handle(cx).focus(window);
1093 }
1094 ActiveView::TextThread { context_editor, .. } => {
1095 context_editor.focus_handle(cx).focus(window);
1096 }
1097 _ => {}
1098 }
1099 } else {
1100 self.active_view =
1101 ActiveView::thread(self.thread.read(cx).thread().clone(), window, cx);
1102 self.message_editor.focus_handle(cx).focus(window);
1103 }
1104 cx.notify();
1105 }
1106 _ => {}
1107 }
1108 }
1109
1110 pub fn toggle_navigation_menu(
1111 &mut self,
1112 _: &ToggleNavigationMenu,
1113 window: &mut Window,
1114 cx: &mut Context<Self>,
1115 ) {
1116 self.assistant_navigation_menu_handle.toggle(window, cx);
1117 }
1118
1119 pub fn toggle_options_menu(
1120 &mut self,
1121 _: &ToggleOptionsMenu,
1122 window: &mut Window,
1123 cx: &mut Context<Self>,
1124 ) {
1125 self.assistant_dropdown_menu_handle.toggle(window, cx);
1126 }
1127
1128 pub fn increase_font_size(
1129 &mut self,
1130 action: &IncreaseBufferFontSize,
1131 _: &mut Window,
1132 cx: &mut Context<Self>,
1133 ) {
1134 self.handle_font_size_action(action.persist, px(1.0), cx);
1135 }
1136
1137 pub fn decrease_font_size(
1138 &mut self,
1139 action: &DecreaseBufferFontSize,
1140 _: &mut Window,
1141 cx: &mut Context<Self>,
1142 ) {
1143 self.handle_font_size_action(action.persist, px(-1.0), cx);
1144 }
1145
1146 fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1147 match self.active_view.which_font_size_used() {
1148 WhichFontSize::AgentFont => {
1149 if persist {
1150 update_settings_file::<ThemeSettings>(
1151 self.fs.clone(),
1152 cx,
1153 move |settings, cx| {
1154 let agent_font_size =
1155 ThemeSettings::get_global(cx).agent_font_size(cx) + delta;
1156 let _ = settings
1157 .agent_font_size
1158 .insert(theme::clamp_font_size(agent_font_size).0);
1159 },
1160 );
1161 } else {
1162 theme::adjust_agent_font_size(cx, |size| {
1163 *size += delta;
1164 });
1165 }
1166 }
1167 WhichFontSize::BufferFont => {
1168 // Prompt editor uses the buffer font size, so allow the action to propagate to the
1169 // default handler that changes that font size.
1170 cx.propagate();
1171 }
1172 WhichFontSize::None => {}
1173 }
1174 }
1175
1176 pub fn reset_font_size(
1177 &mut self,
1178 action: &ResetBufferFontSize,
1179 _: &mut Window,
1180 cx: &mut Context<Self>,
1181 ) {
1182 if action.persist {
1183 update_settings_file::<ThemeSettings>(self.fs.clone(), cx, move |settings, _| {
1184 settings.agent_font_size = None;
1185 });
1186 } else {
1187 theme::reset_agent_font_size(cx);
1188 }
1189 }
1190
1191 pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1192 if self.zoomed {
1193 cx.emit(PanelEvent::ZoomOut);
1194 } else {
1195 if !self.focus_handle(cx).contains_focused(window, cx) {
1196 cx.focus_self(window);
1197 }
1198 cx.emit(PanelEvent::ZoomIn);
1199 }
1200 }
1201
1202 pub fn open_agent_diff(
1203 &mut self,
1204 _: &OpenAgentDiff,
1205 window: &mut Window,
1206 cx: &mut Context<Self>,
1207 ) {
1208 let thread = self.thread.read(cx).thread().clone();
1209 self.workspace
1210 .update(cx, |workspace, cx| {
1211 AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx)
1212 })
1213 .log_err();
1214 }
1215
1216 pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1217 let context_server_store = self.project.read(cx).context_server_store();
1218 let tools = self.thread_store.read(cx).tools();
1219 let fs = self.fs.clone();
1220
1221 self.set_active_view(ActiveView::Configuration, window, cx);
1222 self.configuration =
1223 Some(cx.new(|cx| AgentConfiguration::new(fs, context_server_store, tools, window, cx)));
1224
1225 if let Some(configuration) = self.configuration.as_ref() {
1226 self.configuration_subscription = Some(cx.subscribe_in(
1227 configuration,
1228 window,
1229 Self::handle_agent_configuration_event,
1230 ));
1231
1232 configuration.focus_handle(cx).focus(window);
1233 }
1234 }
1235
1236 pub(crate) fn open_active_thread_as_markdown(
1237 &mut self,
1238 _: &OpenActiveThreadAsMarkdown,
1239 window: &mut Window,
1240 cx: &mut Context<Self>,
1241 ) {
1242 let Some(workspace) = self.workspace.upgrade() else {
1243 return;
1244 };
1245
1246 let Some(thread) = self.active_thread() else {
1247 return;
1248 };
1249
1250 active_thread::open_active_thread_as_markdown(thread, workspace, window, cx)
1251 .detach_and_log_err(cx);
1252 }
1253
1254 fn handle_agent_configuration_event(
1255 &mut self,
1256 _entity: &Entity<AgentConfiguration>,
1257 event: &AssistantConfigurationEvent,
1258 window: &mut Window,
1259 cx: &mut Context<Self>,
1260 ) {
1261 match event {
1262 AssistantConfigurationEvent::NewThread(provider) => {
1263 if LanguageModelRegistry::read_global(cx)
1264 .default_model()
1265 .map_or(true, |model| model.provider.id() != provider.id())
1266 {
1267 if let Some(model) = provider.default_model(cx) {
1268 update_settings_file::<AgentSettings>(
1269 self.fs.clone(),
1270 cx,
1271 move |settings, _| settings.set_model(model),
1272 );
1273 }
1274 }
1275
1276 self.new_thread(&NewThread::default(), window, cx);
1277 }
1278 }
1279 }
1280
1281 pub(crate) fn active_thread(&self) -> Option<Entity<Thread>> {
1282 match &self.active_view {
1283 ActiveView::Thread { thread, .. } => thread.upgrade(),
1284 _ => None,
1285 }
1286 }
1287
1288 pub(crate) fn delete_thread(
1289 &mut self,
1290 thread_id: &ThreadId,
1291 cx: &mut Context<Self>,
1292 ) -> Task<Result<()>> {
1293 self.thread_store
1294 .update(cx, |this, cx| this.delete_thread(thread_id, cx))
1295 }
1296
1297 pub(crate) fn has_active_thread(&self) -> bool {
1298 matches!(self.active_view, ActiveView::Thread { .. })
1299 }
1300
1301 fn continue_conversation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1302 let thread_state = self.thread.read(cx).thread().read(cx);
1303 if !thread_state.tool_use_limit_reached() {
1304 return;
1305 }
1306
1307 let model = thread_state.configured_model().map(|cm| cm.model.clone());
1308 if let Some(model) = model {
1309 self.thread.update(cx, |active_thread, cx| {
1310 active_thread.thread().update(cx, |thread, cx| {
1311 thread.insert_invisible_continue_message(cx);
1312 thread.advance_prompt_id();
1313 thread.send_to_model(model, Some(window.window_handle()), cx);
1314 });
1315 });
1316 } else {
1317 log::warn!("No configured model available for continuation");
1318 }
1319 }
1320
1321 fn toggle_burn_mode(
1322 &mut self,
1323 _: &ToggleBurnMode,
1324 _window: &mut Window,
1325 cx: &mut Context<Self>,
1326 ) {
1327 self.thread.update(cx, |active_thread, cx| {
1328 active_thread.thread().update(cx, |thread, _cx| {
1329 let current_mode = thread.completion_mode();
1330
1331 thread.set_completion_mode(match current_mode {
1332 CompletionMode::Burn => CompletionMode::Normal,
1333 CompletionMode::Normal => CompletionMode::Burn,
1334 });
1335 });
1336 });
1337 }
1338
1339 pub(crate) fn active_context_editor(&self) -> Option<Entity<ContextEditor>> {
1340 match &self.active_view {
1341 ActiveView::TextThread { context_editor, .. } => Some(context_editor.clone()),
1342 _ => None,
1343 }
1344 }
1345
1346 pub(crate) fn delete_context(
1347 &mut self,
1348 path: Arc<Path>,
1349 cx: &mut Context<Self>,
1350 ) -> Task<Result<()>> {
1351 self.context_store
1352 .update(cx, |this, cx| this.delete_local_context(path, cx))
1353 }
1354
1355 fn set_active_view(
1356 &mut self,
1357 new_view: ActiveView,
1358 window: &mut Window,
1359 cx: &mut Context<Self>,
1360 ) {
1361 let current_is_history = matches!(self.active_view, ActiveView::History);
1362 let new_is_history = matches!(new_view, ActiveView::History);
1363
1364 let current_is_config = matches!(self.active_view, ActiveView::Configuration);
1365 let new_is_config = matches!(new_view, ActiveView::Configuration);
1366
1367 let current_is_special = current_is_history || current_is_config;
1368 let new_is_special = new_is_history || new_is_config;
1369
1370 match &self.active_view {
1371 ActiveView::Thread { thread, .. } => {
1372 if let Some(thread) = thread.upgrade() {
1373 if thread.read(cx).is_empty() {
1374 let id = thread.read(cx).id().clone();
1375 self.history_store.update(cx, |store, cx| {
1376 store.remove_recently_opened_thread(id, cx);
1377 });
1378 }
1379 }
1380 }
1381 ActiveView::TextThread { context_editor, .. } => {
1382 let context = context_editor.read(cx).context();
1383 // When switching away from an unsaved text thread, delete its entry.
1384 if context.read(cx).path().is_none() {
1385 let context = context.clone();
1386 self.history_store.update(cx, |store, cx| {
1387 store.remove_recently_opened_entry(&RecentEntry::Context(context), cx);
1388 });
1389 }
1390 }
1391 _ => {}
1392 }
1393
1394 match &new_view {
1395 ActiveView::Thread { thread, .. } => self.history_store.update(cx, |store, cx| {
1396 if let Some(thread) = thread.upgrade() {
1397 let id = thread.read(cx).id().clone();
1398 store.push_recently_opened_entry(RecentEntry::Thread(id, thread), cx);
1399 }
1400 }),
1401 ActiveView::TextThread { context_editor, .. } => {
1402 self.history_store.update(cx, |store, cx| {
1403 let context = context_editor.read(cx).context().clone();
1404 store.push_recently_opened_entry(RecentEntry::Context(context), cx)
1405 })
1406 }
1407 _ => {}
1408 }
1409
1410 if current_is_special && !new_is_special {
1411 self.active_view = new_view;
1412 } else if !current_is_special && new_is_special {
1413 self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
1414 } else {
1415 if !new_is_special {
1416 self.previous_view = None;
1417 }
1418 self.active_view = new_view;
1419 }
1420
1421 self.focus_handle(cx).focus(window);
1422 }
1423}
1424
1425impl Focusable for AgentPanel {
1426 fn focus_handle(&self, cx: &App) -> FocusHandle {
1427 match &self.active_view {
1428 ActiveView::Thread { .. } => self.message_editor.focus_handle(cx),
1429 ActiveView::History => self.history.focus_handle(cx),
1430 ActiveView::TextThread { context_editor, .. } => context_editor.focus_handle(cx),
1431 ActiveView::Configuration => {
1432 if let Some(configuration) = self.configuration.as_ref() {
1433 configuration.focus_handle(cx)
1434 } else {
1435 cx.focus_handle()
1436 }
1437 }
1438 }
1439 }
1440}
1441
1442fn agent_panel_dock_position(cx: &App) -> DockPosition {
1443 match AgentSettings::get_global(cx).dock {
1444 AgentDockPosition::Left => DockPosition::Left,
1445 AgentDockPosition::Bottom => DockPosition::Bottom,
1446 AgentDockPosition::Right => DockPosition::Right,
1447 }
1448}
1449
1450impl EventEmitter<PanelEvent> for AgentPanel {}
1451
1452impl Panel for AgentPanel {
1453 fn persistent_name() -> &'static str {
1454 "AgentPanel"
1455 }
1456
1457 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1458 agent_panel_dock_position(cx)
1459 }
1460
1461 fn position_is_valid(&self, position: DockPosition) -> bool {
1462 position != DockPosition::Bottom
1463 }
1464
1465 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1466 settings::update_settings_file::<AgentSettings>(self.fs.clone(), cx, move |settings, _| {
1467 let dock = match position {
1468 DockPosition::Left => AgentDockPosition::Left,
1469 DockPosition::Bottom => AgentDockPosition::Bottom,
1470 DockPosition::Right => AgentDockPosition::Right,
1471 };
1472 settings.set_dock(dock);
1473 });
1474 }
1475
1476 fn size(&self, window: &Window, cx: &App) -> Pixels {
1477 let settings = AgentSettings::get_global(cx);
1478 match self.position(window, cx) {
1479 DockPosition::Left | DockPosition::Right => {
1480 self.width.unwrap_or(settings.default_width)
1481 }
1482 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1483 }
1484 }
1485
1486 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1487 match self.position(window, cx) {
1488 DockPosition::Left | DockPosition::Right => self.width = size,
1489 DockPosition::Bottom => self.height = size,
1490 }
1491 self.serialize(cx);
1492 cx.notify();
1493 }
1494
1495 fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
1496
1497 fn remote_id() -> Option<proto::PanelId> {
1498 Some(proto::PanelId::AssistantPanel)
1499 }
1500
1501 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1502 (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
1503 }
1504
1505 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1506 Some("Agent Panel")
1507 }
1508
1509 fn toggle_action(&self) -> Box<dyn Action> {
1510 Box::new(ToggleFocus)
1511 }
1512
1513 fn activation_priority(&self) -> u32 {
1514 3
1515 }
1516
1517 fn enabled(&self, cx: &App) -> bool {
1518 AgentSettings::get_global(cx).enabled
1519 }
1520
1521 fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1522 self.zoomed
1523 }
1524
1525 fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1526 self.zoomed = zoomed;
1527 cx.notify();
1528 }
1529}
1530
1531impl AgentPanel {
1532 fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
1533 const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
1534
1535 let content = match &self.active_view {
1536 ActiveView::Thread {
1537 change_title_editor,
1538 ..
1539 } => {
1540 let active_thread = self.thread.read(cx);
1541 let state = if active_thread.is_empty() {
1542 &ThreadSummary::Pending
1543 } else {
1544 active_thread.summary(cx)
1545 };
1546
1547 match state {
1548 ThreadSummary::Pending => Label::new(ThreadSummary::DEFAULT.clone())
1549 .truncate()
1550 .into_any_element(),
1551 ThreadSummary::Generating => Label::new(LOADING_SUMMARY_PLACEHOLDER)
1552 .truncate()
1553 .into_any_element(),
1554 ThreadSummary::Ready(_) => div()
1555 .w_full()
1556 .child(change_title_editor.clone())
1557 .into_any_element(),
1558 ThreadSummary::Error => h_flex()
1559 .w_full()
1560 .child(change_title_editor.clone())
1561 .child(
1562 ui::IconButton::new("retry-summary-generation", IconName::RotateCcw)
1563 .on_click({
1564 let active_thread = self.thread.clone();
1565 move |_, _window, cx| {
1566 active_thread.update(cx, |thread, cx| {
1567 thread.regenerate_summary(cx);
1568 });
1569 }
1570 })
1571 .tooltip(move |_window, cx| {
1572 cx.new(|_| {
1573 Tooltip::new("Failed to generate title")
1574 .meta("Click to try again")
1575 })
1576 .into()
1577 }),
1578 )
1579 .into_any_element(),
1580 }
1581 }
1582 ActiveView::TextThread {
1583 title_editor,
1584 context_editor,
1585 ..
1586 } => {
1587 let summary = context_editor.read(cx).context().read(cx).summary();
1588
1589 match summary {
1590 ContextSummary::Pending => Label::new(ContextSummary::DEFAULT)
1591 .truncate()
1592 .into_any_element(),
1593 ContextSummary::Content(summary) => {
1594 if summary.done {
1595 div()
1596 .w_full()
1597 .child(title_editor.clone())
1598 .into_any_element()
1599 } else {
1600 Label::new(LOADING_SUMMARY_PLACEHOLDER)
1601 .truncate()
1602 .into_any_element()
1603 }
1604 }
1605 ContextSummary::Error => h_flex()
1606 .w_full()
1607 .child(title_editor.clone())
1608 .child(
1609 ui::IconButton::new("retry-summary-generation", IconName::RotateCcw)
1610 .on_click({
1611 let context_editor = context_editor.clone();
1612 move |_, _window, cx| {
1613 context_editor.update(cx, |context_editor, cx| {
1614 context_editor.regenerate_summary(cx);
1615 });
1616 }
1617 })
1618 .tooltip(move |_window, cx| {
1619 cx.new(|_| {
1620 Tooltip::new("Failed to generate title")
1621 .meta("Click to try again")
1622 })
1623 .into()
1624 }),
1625 )
1626 .into_any_element(),
1627 }
1628 }
1629 ActiveView::History => Label::new("History").truncate().into_any_element(),
1630 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
1631 };
1632
1633 h_flex()
1634 .key_context("TitleEditor")
1635 .id("TitleEditor")
1636 .flex_grow()
1637 .w_full()
1638 .max_w_full()
1639 .overflow_x_scroll()
1640 .child(content)
1641 .into_any()
1642 }
1643
1644 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1645 let active_thread = self.thread.read(cx);
1646 let user_store = self.user_store.read(cx);
1647 let thread = active_thread.thread().read(cx);
1648 let thread_id = thread.id().clone();
1649 let is_empty = active_thread.is_empty();
1650 let editor_empty = self.message_editor.read(cx).is_editor_fully_empty(cx);
1651 let last_usage = active_thread.thread().read(cx).last_usage().or_else(|| {
1652 maybe!({
1653 let amount = user_store.model_request_usage_amount()?;
1654 let limit = user_store.model_request_usage_limit()?.variant?;
1655
1656 Some(RequestUsage {
1657 amount: amount as i32,
1658 limit: match limit {
1659 proto::usage_limit::Variant::Limited(limited) => {
1660 zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1661 }
1662 proto::usage_limit::Variant::Unlimited(_) => {
1663 zed_llm_client::UsageLimit::Unlimited
1664 }
1665 },
1666 })
1667 })
1668 });
1669
1670 let account_url = zed_urls::account_url(cx);
1671
1672 let show_token_count = match &self.active_view {
1673 ActiveView::Thread { .. } => !is_empty || !editor_empty,
1674 ActiveView::TextThread { .. } => true,
1675 _ => false,
1676 };
1677
1678 let focus_handle = self.focus_handle(cx);
1679
1680 let go_back_button = div().child(
1681 IconButton::new("go-back", IconName::ArrowLeft)
1682 .icon_size(IconSize::Small)
1683 .on_click(cx.listener(|this, _, window, cx| {
1684 this.go_back(&workspace::GoBack, window, cx);
1685 }))
1686 .tooltip({
1687 let focus_handle = focus_handle.clone();
1688 move |window, cx| {
1689 Tooltip::for_action_in(
1690 "Go Back",
1691 &workspace::GoBack,
1692 &focus_handle,
1693 window,
1694 cx,
1695 )
1696 }
1697 }),
1698 );
1699
1700 let recent_entries_menu = div().child(
1701 PopoverMenu::new("agent-nav-menu")
1702 .trigger_with_tooltip(
1703 IconButton::new("agent-nav-menu", IconName::MenuAlt)
1704 .icon_size(IconSize::Small)
1705 .style(ui::ButtonStyle::Subtle),
1706 {
1707 let focus_handle = focus_handle.clone();
1708 move |window, cx| {
1709 Tooltip::for_action_in(
1710 "Toggle Panel Menu",
1711 &ToggleNavigationMenu,
1712 &focus_handle,
1713 window,
1714 cx,
1715 )
1716 }
1717 },
1718 )
1719 .anchor(Corner::TopLeft)
1720 .with_handle(self.assistant_navigation_menu_handle.clone())
1721 .menu({
1722 let menu = self.assistant_navigation_menu.clone();
1723 move |window, cx| {
1724 if let Some(menu) = menu.as_ref() {
1725 menu.update(cx, |_, cx| {
1726 cx.defer_in(window, |menu, window, cx| {
1727 menu.rebuild(window, cx);
1728 });
1729 })
1730 }
1731 menu.clone()
1732 }
1733 }),
1734 );
1735
1736 let zoom_in_label = if self.is_zoomed(window, cx) {
1737 "Zoom Out"
1738 } else {
1739 "Zoom In"
1740 };
1741
1742 let agent_extra_menu = PopoverMenu::new("agent-options-menu")
1743 .trigger_with_tooltip(
1744 IconButton::new("agent-options-menu", IconName::Ellipsis)
1745 .icon_size(IconSize::Small),
1746 {
1747 let focus_handle = focus_handle.clone();
1748 move |window, cx| {
1749 Tooltip::for_action_in(
1750 "Toggle Agent Menu",
1751 &ToggleOptionsMenu,
1752 &focus_handle,
1753 window,
1754 cx,
1755 )
1756 }
1757 },
1758 )
1759 .anchor(Corner::TopRight)
1760 .with_handle(self.assistant_dropdown_menu_handle.clone())
1761 .menu(move |window, cx| {
1762 Some(ContextMenu::build(window, cx, |mut menu, _window, _cx| {
1763 menu = menu
1764 .action("New Thread", NewThread::default().boxed_clone())
1765 .action("New Text Thread", NewTextThread.boxed_clone())
1766 .when(!is_empty, |menu| {
1767 menu.action(
1768 "New From Summary",
1769 Box::new(NewThread {
1770 from_thread_id: Some(thread_id.clone()),
1771 }),
1772 )
1773 })
1774 .separator();
1775
1776 menu = menu
1777 .header("MCP Servers")
1778 .action(
1779 "View Server Extensions",
1780 Box::new(zed_actions::Extensions {
1781 category_filter: Some(
1782 zed_actions::ExtensionCategoryFilter::ContextServers,
1783 ),
1784 }),
1785 )
1786 .action("Add Custom Server…", Box::new(AddContextServer))
1787 .separator();
1788
1789 if let Some(usage) = last_usage {
1790 menu = menu
1791 .header_with_link("Prompt Usage", "Manage", account_url.clone())
1792 .custom_entry(
1793 move |_window, cx| {
1794 let used_percentage = match usage.limit {
1795 UsageLimit::Limited(limit) => {
1796 Some((usage.amount as f32 / limit as f32) * 100.)
1797 }
1798 UsageLimit::Unlimited => None,
1799 };
1800
1801 h_flex()
1802 .flex_1()
1803 .gap_1p5()
1804 .children(used_percentage.map(|percent| {
1805 ProgressBar::new("usage", percent, 100., cx)
1806 }))
1807 .child(
1808 Label::new(match usage.limit {
1809 UsageLimit::Limited(limit) => {
1810 format!("{} / {limit}", usage.amount)
1811 }
1812 UsageLimit::Unlimited => {
1813 format!("{} / ∞", usage.amount)
1814 }
1815 })
1816 .size(LabelSize::Small)
1817 .color(Color::Muted),
1818 )
1819 .into_any_element()
1820 },
1821 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
1822 )
1823 .separator()
1824 }
1825
1826 menu = menu
1827 .action("Rules…", Box::new(OpenRulesLibrary::default()))
1828 .action("Settings", Box::new(OpenConfiguration))
1829 .action(zoom_in_label, Box::new(ToggleZoom));
1830 menu
1831 }))
1832 });
1833
1834 h_flex()
1835 .id("assistant-toolbar")
1836 .h(Tab::container_height(cx))
1837 .max_w_full()
1838 .flex_none()
1839 .justify_between()
1840 .gap_2()
1841 .bg(cx.theme().colors().tab_bar_background)
1842 .border_b_1()
1843 .border_color(cx.theme().colors().border)
1844 .child(
1845 h_flex()
1846 .size_full()
1847 .pl_1()
1848 .gap_1()
1849 .child(match &self.active_view {
1850 ActiveView::History | ActiveView::Configuration => go_back_button,
1851 _ => recent_entries_menu,
1852 })
1853 .child(self.render_title_view(window, cx)),
1854 )
1855 .child(
1856 h_flex()
1857 .h_full()
1858 .gap_2()
1859 .when(show_token_count, |parent| {
1860 parent.children(self.render_token_count(&thread, cx))
1861 })
1862 .child(
1863 h_flex()
1864 .h_full()
1865 .gap(DynamicSpacing::Base02.rems(cx))
1866 .px(DynamicSpacing::Base08.rems(cx))
1867 .border_l_1()
1868 .border_color(cx.theme().colors().border)
1869 .child(
1870 IconButton::new("new", IconName::Plus)
1871 .icon_size(IconSize::Small)
1872 .style(ButtonStyle::Subtle)
1873 .tooltip(move |window, cx| {
1874 Tooltip::for_action_in(
1875 "New Thread",
1876 &NewThread::default(),
1877 &focus_handle,
1878 window,
1879 cx,
1880 )
1881 })
1882 .on_click(move |_event, window, cx| {
1883 window.dispatch_action(
1884 NewThread::default().boxed_clone(),
1885 cx,
1886 );
1887 }),
1888 )
1889 .child(agent_extra_menu),
1890 ),
1891 )
1892 }
1893
1894 fn render_token_count(&self, thread: &Thread, cx: &App) -> Option<AnyElement> {
1895 let is_generating = thread.is_generating();
1896 let message_editor = self.message_editor.read(cx);
1897
1898 let conversation_token_usage = thread.total_token_usage()?;
1899
1900 let (total_token_usage, is_estimating) = if let Some((editing_message_id, unsent_tokens)) =
1901 self.thread.read(cx).editing_message_id()
1902 {
1903 let combined = thread
1904 .token_usage_up_to_message(editing_message_id)
1905 .add(unsent_tokens);
1906
1907 (combined, unsent_tokens > 0)
1908 } else {
1909 let unsent_tokens = message_editor.last_estimated_token_count().unwrap_or(0);
1910 let combined = conversation_token_usage.add(unsent_tokens);
1911
1912 (combined, unsent_tokens > 0)
1913 };
1914
1915 let is_waiting_to_update_token_count = message_editor.is_waiting_to_update_token_count();
1916
1917 match &self.active_view {
1918 ActiveView::Thread { .. } => {
1919 if total_token_usage.total == 0 {
1920 return None;
1921 }
1922
1923 let token_color = match total_token_usage.ratio() {
1924 TokenUsageRatio::Normal if is_estimating => Color::Default,
1925 TokenUsageRatio::Normal => Color::Muted,
1926 TokenUsageRatio::Warning => Color::Warning,
1927 TokenUsageRatio::Exceeded => Color::Error,
1928 };
1929
1930 let token_count = h_flex()
1931 .id("token-count")
1932 .flex_shrink_0()
1933 .gap_0p5()
1934 .when(!is_generating && is_estimating, |parent| {
1935 parent
1936 .child(
1937 h_flex()
1938 .mr_1()
1939 .size_2p5()
1940 .justify_center()
1941 .rounded_full()
1942 .bg(cx.theme().colors().text.opacity(0.1))
1943 .child(
1944 div().size_1().rounded_full().bg(cx.theme().colors().text),
1945 ),
1946 )
1947 .tooltip(move |window, cx| {
1948 Tooltip::with_meta(
1949 "Estimated New Token Count",
1950 None,
1951 format!(
1952 "Current Conversation Tokens: {}",
1953 humanize_token_count(conversation_token_usage.total)
1954 ),
1955 window,
1956 cx,
1957 )
1958 })
1959 })
1960 .child(
1961 Label::new(humanize_token_count(total_token_usage.total))
1962 .size(LabelSize::Small)
1963 .color(token_color)
1964 .map(|label| {
1965 if is_generating || is_waiting_to_update_token_count {
1966 label
1967 .with_animation(
1968 "used-tokens-label",
1969 Animation::new(Duration::from_secs(2))
1970 .repeat()
1971 .with_easing(pulsating_between(0.6, 1.)),
1972 |label, delta| label.alpha(delta),
1973 )
1974 .into_any()
1975 } else {
1976 label.into_any_element()
1977 }
1978 }),
1979 )
1980 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1981 .child(
1982 Label::new(humanize_token_count(total_token_usage.max))
1983 .size(LabelSize::Small)
1984 .color(Color::Muted),
1985 )
1986 .into_any();
1987
1988 Some(token_count)
1989 }
1990 ActiveView::TextThread { context_editor, .. } => {
1991 let element = render_remaining_tokens(context_editor, cx)?;
1992
1993 Some(element.into_any_element())
1994 }
1995 _ => None,
1996 }
1997 }
1998
1999 fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
2000 if TrialEndUpsell::dismissed() {
2001 return false;
2002 }
2003
2004 let plan = self.user_store.read(cx).current_plan();
2005 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2006
2007 matches!(plan, Some(Plan::Free)) && has_previous_trial
2008 }
2009
2010 fn should_render_upsell(&self, cx: &mut Context<Self>) -> bool {
2011 if !matches!(self.active_view, ActiveView::Thread { .. }) {
2012 return false;
2013 }
2014
2015 if self.hide_upsell || Upsell::dismissed() {
2016 return false;
2017 }
2018
2019 let is_using_zed_provider = self
2020 .thread
2021 .read(cx)
2022 .thread()
2023 .read(cx)
2024 .configured_model()
2025 .map_or(false, |model| {
2026 model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
2027 });
2028 if !is_using_zed_provider {
2029 return false;
2030 }
2031
2032 let plan = self.user_store.read(cx).current_plan();
2033 if matches!(plan, Some(Plan::ZedPro | Plan::ZedProTrial)) {
2034 return false;
2035 }
2036
2037 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2038 if has_previous_trial {
2039 return false;
2040 }
2041
2042 true
2043 }
2044
2045 fn render_upsell(
2046 &self,
2047 _window: &mut Window,
2048 cx: &mut Context<Self>,
2049 ) -> Option<impl IntoElement> {
2050 if !self.should_render_upsell(cx) {
2051 return None;
2052 }
2053
2054 if self.user_store.read(cx).account_too_young() {
2055 Some(self.render_young_account_upsell(cx).into_any_element())
2056 } else {
2057 Some(self.render_trial_upsell(cx).into_any_element())
2058 }
2059 }
2060
2061 fn render_young_account_upsell(&self, cx: &mut Context<Self>) -> impl IntoElement {
2062 let checkbox = CheckboxWithLabel::new(
2063 "dont-show-again",
2064 Label::new("Don't show again").color(Color::Muted),
2065 ToggleState::Unselected,
2066 move |toggle_state, _window, cx| {
2067 let toggle_state_bool = toggle_state.selected();
2068
2069 Upsell::set_dismissed(toggle_state_bool, cx);
2070 },
2071 );
2072
2073 let contents = div()
2074 .size_full()
2075 .gap_2()
2076 .flex()
2077 .flex_col()
2078 .child(Headline::new("Build better with Zed Pro").size(HeadlineSize::Small))
2079 .child(
2080 Label::new("Your GitHub account was created less than 30 days ago, so we can't offer you a free trial.")
2081 .size(LabelSize::Small),
2082 )
2083 .child(
2084 Label::new(
2085 "Use your own API keys, upgrade to Zed Pro or send an email to billing-support@zed.dev.",
2086 )
2087 .color(Color::Muted),
2088 )
2089 .child(
2090 h_flex()
2091 .w_full()
2092 .px_neg_1()
2093 .justify_between()
2094 .items_center()
2095 .child(h_flex().items_center().gap_1().child(checkbox))
2096 .child(
2097 h_flex()
2098 .gap_2()
2099 .child(
2100 Button::new("dismiss-button", "Not Now")
2101 .style(ButtonStyle::Transparent)
2102 .color(Color::Muted)
2103 .on_click({
2104 let agent_panel = cx.entity();
2105 move |_, _, cx| {
2106 agent_panel.update(cx, |this, cx| {
2107 this.hide_upsell = true;
2108 cx.notify();
2109 });
2110 }
2111 }),
2112 )
2113 .child(
2114 Button::new("cta-button", "Upgrade to Zed Pro")
2115 .style(ButtonStyle::Transparent)
2116 .on_click(|_, _, cx| cx.open_url(&zed_urls::account_url(cx))),
2117 ),
2118 ),
2119 );
2120
2121 self.render_upsell_container(cx, contents)
2122 }
2123
2124 fn render_trial_upsell(&self, cx: &mut Context<Self>) -> impl IntoElement {
2125 let checkbox = CheckboxWithLabel::new(
2126 "dont-show-again",
2127 Label::new("Don't show again").color(Color::Muted),
2128 ToggleState::Unselected,
2129 move |toggle_state, _window, cx| {
2130 let toggle_state_bool = toggle_state.selected();
2131
2132 Upsell::set_dismissed(toggle_state_bool, cx);
2133 },
2134 );
2135
2136 let contents = div()
2137 .size_full()
2138 .gap_2()
2139 .flex()
2140 .flex_col()
2141 .child(Headline::new("Build better with Zed Pro").size(HeadlineSize::Small))
2142 .child(
2143 Label::new("Try Zed Pro for free for 14 days - no credit card required.")
2144 .size(LabelSize::Small),
2145 )
2146 .child(
2147 Label::new(
2148 "Use your own API keys or enable usage-based billing once you hit the cap.",
2149 )
2150 .color(Color::Muted),
2151 )
2152 .child(
2153 h_flex()
2154 .w_full()
2155 .px_neg_1()
2156 .justify_between()
2157 .items_center()
2158 .child(h_flex().items_center().gap_1().child(checkbox))
2159 .child(
2160 h_flex()
2161 .gap_2()
2162 .child(
2163 Button::new("dismiss-button", "Not Now")
2164 .style(ButtonStyle::Transparent)
2165 .color(Color::Muted)
2166 .on_click({
2167 let agent_panel = cx.entity();
2168 move |_, _, cx| {
2169 agent_panel.update(cx, |this, cx| {
2170 this.hide_upsell = true;
2171 cx.notify();
2172 });
2173 }
2174 }),
2175 )
2176 .child(
2177 Button::new("cta-button", "Start Trial")
2178 .style(ButtonStyle::Transparent)
2179 .on_click(|_, _, cx| cx.open_url(&zed_urls::account_url(cx))),
2180 ),
2181 ),
2182 );
2183
2184 self.render_upsell_container(cx, contents)
2185 }
2186
2187 fn render_trial_end_upsell(
2188 &self,
2189 _window: &mut Window,
2190 cx: &mut Context<Self>,
2191 ) -> Option<impl IntoElement> {
2192 if !self.should_render_trial_end_upsell(cx) {
2193 return None;
2194 }
2195
2196 Some(
2197 self.render_upsell_container(
2198 cx,
2199 div()
2200 .size_full()
2201 .gap_2()
2202 .flex()
2203 .flex_col()
2204 .child(
2205 Headline::new("Your Zed Pro trial has expired.").size(HeadlineSize::Small),
2206 )
2207 .child(
2208 Label::new("You've been automatically reset to the free plan.")
2209 .size(LabelSize::Small),
2210 )
2211 .child(
2212 h_flex()
2213 .w_full()
2214 .px_neg_1()
2215 .justify_between()
2216 .items_center()
2217 .child(div())
2218 .child(
2219 h_flex()
2220 .gap_2()
2221 .child(
2222 Button::new("dismiss-button", "Stay on Free")
2223 .style(ButtonStyle::Transparent)
2224 .color(Color::Muted)
2225 .on_click({
2226 let agent_panel = cx.entity();
2227 move |_, _, cx| {
2228 agent_panel.update(cx, |_this, cx| {
2229 TrialEndUpsell::set_dismissed(true, cx);
2230 cx.notify();
2231 });
2232 }
2233 }),
2234 )
2235 .child(
2236 Button::new("cta-button", "Upgrade to Zed Pro")
2237 .style(ButtonStyle::Transparent)
2238 .on_click(|_, _, cx| {
2239 cx.open_url(&zed_urls::account_url(cx))
2240 }),
2241 ),
2242 ),
2243 ),
2244 ),
2245 )
2246 }
2247
2248 fn render_upsell_container(&self, cx: &mut Context<Self>, content: Div) -> Div {
2249 div().p_2().child(
2250 v_flex()
2251 .w_full()
2252 .elevation_2(cx)
2253 .rounded(px(8.))
2254 .bg(cx.theme().colors().background.alpha(0.5))
2255 .p(px(3.))
2256 .child(
2257 div()
2258 .gap_2()
2259 .flex()
2260 .flex_col()
2261 .size_full()
2262 .border_1()
2263 .rounded(px(5.))
2264 .border_color(cx.theme().colors().text.alpha(0.1))
2265 .overflow_hidden()
2266 .relative()
2267 .bg(cx.theme().colors().panel_background)
2268 .px_4()
2269 .py_3()
2270 .child(
2271 div()
2272 .absolute()
2273 .top_0()
2274 .right(px(-1.0))
2275 .w(px(441.))
2276 .h(px(167.))
2277 .child(
2278 Vector::new(
2279 VectorName::Grid,
2280 rems_from_px(441.),
2281 rems_from_px(167.),
2282 )
2283 .color(ui::Color::Custom(cx.theme().colors().text.alpha(0.1))),
2284 ),
2285 )
2286 .child(
2287 div()
2288 .absolute()
2289 .top(px(-8.0))
2290 .right_0()
2291 .w(px(400.))
2292 .h(px(92.))
2293 .child(
2294 Vector::new(
2295 VectorName::AiGrid,
2296 rems_from_px(400.),
2297 rems_from_px(92.),
2298 )
2299 .color(ui::Color::Custom(cx.theme().colors().text.alpha(0.32))),
2300 ),
2301 )
2302 // .child(
2303 // div()
2304 // .absolute()
2305 // .top_0()
2306 // .right(px(360.))
2307 // .size(px(401.))
2308 // .overflow_hidden()
2309 // .bg(cx.theme().colors().panel_background)
2310 // )
2311 .child(
2312 div()
2313 .absolute()
2314 .top_0()
2315 .right_0()
2316 .w(px(660.))
2317 .h(px(401.))
2318 .overflow_hidden()
2319 .bg(linear_gradient(
2320 75.,
2321 linear_color_stop(
2322 cx.theme().colors().panel_background.alpha(0.01),
2323 1.0,
2324 ),
2325 linear_color_stop(cx.theme().colors().panel_background, 0.45),
2326 )),
2327 )
2328 .child(content),
2329 ),
2330 )
2331 }
2332
2333 fn render_active_thread_or_empty_state(
2334 &self,
2335 window: &mut Window,
2336 cx: &mut Context<Self>,
2337 ) -> AnyElement {
2338 if self.thread.read(cx).is_empty() {
2339 return self
2340 .render_thread_empty_state(window, cx)
2341 .into_any_element();
2342 }
2343
2344 self.thread.clone().into_any_element()
2345 }
2346
2347 fn configuration_error(&self, cx: &App) -> Option<ConfigurationError> {
2348 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
2349 return Some(ConfigurationError::NoProvider);
2350 };
2351
2352 if !model.provider.is_authenticated(cx) {
2353 return Some(ConfigurationError::ProviderNotAuthenticated);
2354 }
2355
2356 if model.provider.must_accept_terms(cx) {
2357 return Some(ConfigurationError::ProviderPendingTermsAcceptance(
2358 model.provider,
2359 ));
2360 }
2361
2362 None
2363 }
2364
2365 fn render_thread_empty_state(
2366 &self,
2367 window: &mut Window,
2368 cx: &mut Context<Self>,
2369 ) -> impl IntoElement {
2370 let recent_history = self
2371 .history_store
2372 .update(cx, |this, cx| this.recent_entries(6, cx));
2373
2374 let configuration_error = self.configuration_error(cx);
2375 let no_error = configuration_error.is_none();
2376 let focus_handle = self.focus_handle(cx);
2377
2378 v_flex()
2379 .size_full()
2380 .bg(cx.theme().colors().panel_background)
2381 .when(recent_history.is_empty(), |this| {
2382 let configuration_error_ref = &configuration_error;
2383 this.child(
2384 v_flex()
2385 .size_full()
2386 .max_w_80()
2387 .mx_auto()
2388 .justify_center()
2389 .items_center()
2390 .gap_1()
2391 .child(
2392 h_flex().child(
2393 Headline::new("Welcome to the Agent Panel")
2394 ),
2395 )
2396 .when(no_error, |parent| {
2397 parent
2398 .child(
2399 h_flex().child(
2400 Label::new("Ask and build anything.")
2401 .color(Color::Muted)
2402 .mb_2p5(),
2403 ),
2404 )
2405 .child(
2406 Button::new("new-thread", "Start New Thread")
2407 .icon(IconName::Plus)
2408 .icon_position(IconPosition::Start)
2409 .icon_size(IconSize::Small)
2410 .icon_color(Color::Muted)
2411 .full_width()
2412 .key_binding(KeyBinding::for_action_in(
2413 &NewThread::default(),
2414 &focus_handle,
2415 window,
2416 cx,
2417 ))
2418 .on_click(|_event, window, cx| {
2419 window.dispatch_action(NewThread::default().boxed_clone(), cx)
2420 }),
2421 )
2422 .child(
2423 Button::new("context", "Add Context")
2424 .icon(IconName::FileCode)
2425 .icon_position(IconPosition::Start)
2426 .icon_size(IconSize::Small)
2427 .icon_color(Color::Muted)
2428 .full_width()
2429 .key_binding(KeyBinding::for_action_in(
2430 &ToggleContextPicker,
2431 &focus_handle,
2432 window,
2433 cx,
2434 ))
2435 .on_click(|_event, window, cx| {
2436 window.dispatch_action(ToggleContextPicker.boxed_clone(), cx)
2437 }),
2438 )
2439 .child(
2440 Button::new("mode", "Switch Model")
2441 .icon(IconName::DatabaseZap)
2442 .icon_position(IconPosition::Start)
2443 .icon_size(IconSize::Small)
2444 .icon_color(Color::Muted)
2445 .full_width()
2446 .key_binding(KeyBinding::for_action_in(
2447 &ToggleModelSelector,
2448 &focus_handle,
2449 window,
2450 cx,
2451 ))
2452 .on_click(|_event, window, cx| {
2453 window.dispatch_action(ToggleModelSelector.boxed_clone(), cx)
2454 }),
2455 )
2456 .child(
2457 Button::new("settings", "View Settings")
2458 .icon(IconName::Settings)
2459 .icon_position(IconPosition::Start)
2460 .icon_size(IconSize::Small)
2461 .icon_color(Color::Muted)
2462 .full_width()
2463 .key_binding(KeyBinding::for_action_in(
2464 &OpenConfiguration,
2465 &focus_handle,
2466 window,
2467 cx,
2468 ))
2469 .on_click(|_event, window, cx| {
2470 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
2471 }),
2472 )
2473 })
2474 .map(|parent| {
2475 match configuration_error_ref {
2476 Some(ConfigurationError::ProviderNotAuthenticated)
2477 | Some(ConfigurationError::NoProvider) => {
2478 parent
2479 .child(
2480 h_flex().child(
2481 Label::new("To start using the agent, configure at least one LLM provider.")
2482 .color(Color::Muted)
2483 .mb_2p5()
2484 )
2485 )
2486 .child(
2487 Button::new("settings", "Configure a Provider")
2488 .icon(IconName::Settings)
2489 .icon_position(IconPosition::Start)
2490 .icon_size(IconSize::Small)
2491 .icon_color(Color::Muted)
2492 .full_width()
2493 .key_binding(KeyBinding::for_action_in(
2494 &OpenConfiguration,
2495 &focus_handle,
2496 window,
2497 cx,
2498 ))
2499 .on_click(|_event, window, cx| {
2500 window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
2501 }),
2502 )
2503 }
2504 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2505 parent.children(
2506 provider.render_accept_terms(
2507 LanguageModelProviderTosView::ThreadFreshStart,
2508 cx,
2509 ),
2510 )
2511 }
2512 None => parent,
2513 }
2514 })
2515 )
2516 })
2517 .when(!recent_history.is_empty(), |parent| {
2518 let focus_handle = focus_handle.clone();
2519 let configuration_error_ref = &configuration_error;
2520
2521 parent
2522 .overflow_hidden()
2523 .p_1p5()
2524 .justify_end()
2525 .gap_1()
2526 .child(
2527 h_flex()
2528 .pl_1p5()
2529 .pb_1()
2530 .w_full()
2531 .justify_between()
2532 .border_b_1()
2533 .border_color(cx.theme().colors().border_variant)
2534 .child(
2535 Label::new("Recent")
2536 .size(LabelSize::Small)
2537 .color(Color::Muted),
2538 )
2539 .child(
2540 Button::new("view-history", "View All")
2541 .style(ButtonStyle::Subtle)
2542 .label_size(LabelSize::Small)
2543 .key_binding(
2544 KeyBinding::for_action_in(
2545 &OpenHistory,
2546 &self.focus_handle(cx),
2547 window,
2548 cx,
2549 ).map(|kb| kb.size(rems_from_px(12.))),
2550 )
2551 .on_click(move |_event, window, cx| {
2552 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2553 }),
2554 ),
2555 )
2556 .child(
2557 v_flex()
2558 .gap_1()
2559 .children(
2560 recent_history.into_iter().enumerate().map(|(index, entry)| {
2561 // TODO: Add keyboard navigation.
2562 let is_hovered = self.hovered_recent_history_item == Some(index);
2563 HistoryEntryElement::new(entry.clone(), cx.entity().downgrade())
2564 .hovered(is_hovered)
2565 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
2566 if *is_hovered {
2567 this.hovered_recent_history_item = Some(index);
2568 } else if this.hovered_recent_history_item == Some(index) {
2569 this.hovered_recent_history_item = None;
2570 }
2571 cx.notify();
2572 }))
2573 .into_any_element()
2574 }),
2575 )
2576 )
2577 .map(|parent| {
2578 match configuration_error_ref {
2579 Some(ConfigurationError::ProviderNotAuthenticated)
2580 | Some(ConfigurationError::NoProvider) => {
2581 parent
2582 .child(
2583 Banner::new()
2584 .severity(ui::Severity::Warning)
2585 .child(
2586 Label::new(
2587 "Configure at least one LLM provider to start using the panel.",
2588 )
2589 .size(LabelSize::Small),
2590 )
2591 .action_slot(
2592 Button::new("settings", "Configure Provider")
2593 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2594 .label_size(LabelSize::Small)
2595 .key_binding(
2596 KeyBinding::for_action_in(
2597 &OpenConfiguration,
2598 &focus_handle,
2599 window,
2600 cx,
2601 )
2602 .map(|kb| kb.size(rems_from_px(12.))),
2603 )
2604 .on_click(|_event, window, cx| {
2605 window.dispatch_action(
2606 OpenConfiguration.boxed_clone(),
2607 cx,
2608 )
2609 }),
2610 ),
2611 )
2612 }
2613 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2614 parent
2615 .child(
2616 Banner::new()
2617 .severity(ui::Severity::Warning)
2618 .child(
2619 h_flex()
2620 .w_full()
2621 .children(
2622 provider.render_accept_terms(
2623 LanguageModelProviderTosView::ThreadtEmptyState,
2624 cx,
2625 ),
2626 ),
2627 ),
2628 )
2629 }
2630 None => parent,
2631 }
2632 })
2633 })
2634 }
2635
2636 fn render_tool_use_limit_reached(
2637 &self,
2638 window: &mut Window,
2639 cx: &mut Context<Self>,
2640 ) -> Option<AnyElement> {
2641 let tool_use_limit_reached = self
2642 .thread
2643 .read(cx)
2644 .thread()
2645 .read(cx)
2646 .tool_use_limit_reached();
2647 if !tool_use_limit_reached {
2648 return None;
2649 }
2650
2651 let model = self
2652 .thread
2653 .read(cx)
2654 .thread()
2655 .read(cx)
2656 .configured_model()?
2657 .model;
2658
2659 let focus_handle = self.focus_handle(cx);
2660
2661 let banner = Banner::new()
2662 .severity(ui::Severity::Info)
2663 .child(Label::new("Consecutive tool use limit reached.").size(LabelSize::Small))
2664 .action_slot(
2665 h_flex()
2666 .gap_1()
2667 .child(
2668 Button::new("continue-conversation", "Continue")
2669 .layer(ElevationIndex::ModalSurface)
2670 .label_size(LabelSize::Small)
2671 .key_binding(
2672 KeyBinding::for_action_in(
2673 &ContinueThread,
2674 &focus_handle,
2675 window,
2676 cx,
2677 )
2678 .map(|kb| kb.size(rems_from_px(10.))),
2679 )
2680 .on_click(cx.listener(|this, _, window, cx| {
2681 this.continue_conversation(window, cx);
2682 })),
2683 )
2684 .when(model.supports_max_mode(), |this| {
2685 this.child(
2686 Button::new("continue-burn-mode", "Continue with Burn Mode")
2687 .style(ButtonStyle::Filled)
2688 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2689 .layer(ElevationIndex::ModalSurface)
2690 .label_size(LabelSize::Small)
2691 .key_binding(
2692 KeyBinding::for_action_in(
2693 &ContinueWithBurnMode,
2694 &focus_handle,
2695 window,
2696 cx,
2697 )
2698 .map(|kb| kb.size(rems_from_px(10.))),
2699 )
2700 .tooltip(Tooltip::text("Enable Burn Mode for unlimited tool use."))
2701 .on_click(cx.listener(|this, _, window, cx| {
2702 this.thread.update(cx, |active_thread, cx| {
2703 active_thread.thread().update(cx, |thread, _cx| {
2704 thread.set_completion_mode(CompletionMode::Burn);
2705 });
2706 });
2707 this.continue_conversation(window, cx);
2708 })),
2709 )
2710 }),
2711 );
2712
2713 Some(div().px_2().pb_2().child(banner).into_any_element())
2714 }
2715
2716 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2717 let last_error = self.thread.read(cx).last_error()?;
2718
2719 Some(
2720 div()
2721 .absolute()
2722 .right_3()
2723 .bottom_12()
2724 .max_w_96()
2725 .py_2()
2726 .px_3()
2727 .elevation_2(cx)
2728 .occlude()
2729 .child(match last_error {
2730 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
2731 ThreadError::ModelRequestLimitReached { plan } => {
2732 self.render_model_request_limit_reached_error(plan, cx)
2733 }
2734 ThreadError::Message { header, message } => {
2735 self.render_error_message(header, message, cx)
2736 }
2737 })
2738 .into_any(),
2739 )
2740 }
2741
2742 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2743 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.";
2744
2745 v_flex()
2746 .gap_0p5()
2747 .child(
2748 h_flex()
2749 .gap_1p5()
2750 .items_center()
2751 .child(Icon::new(IconName::XCircle).color(Color::Error))
2752 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2753 )
2754 .child(
2755 div()
2756 .id("error-message")
2757 .max_h_24()
2758 .overflow_y_scroll()
2759 .child(Label::new(ERROR_MESSAGE)),
2760 )
2761 .child(
2762 h_flex()
2763 .justify_end()
2764 .mt_1()
2765 .gap_1()
2766 .child(self.create_copy_button(ERROR_MESSAGE))
2767 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2768 |this, _, _, cx| {
2769 this.thread.update(cx, |this, _cx| {
2770 this.clear_last_error();
2771 });
2772
2773 cx.open_url(&zed_urls::account_url(cx));
2774 cx.notify();
2775 },
2776 )))
2777 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2778 |this, _, _, cx| {
2779 this.thread.update(cx, |this, _cx| {
2780 this.clear_last_error();
2781 });
2782
2783 cx.notify();
2784 },
2785 ))),
2786 )
2787 .into_any()
2788 }
2789
2790 fn render_model_request_limit_reached_error(
2791 &self,
2792 plan: Plan,
2793 cx: &mut Context<Self>,
2794 ) -> AnyElement {
2795 let error_message = match plan {
2796 Plan::ZedPro => {
2797 "Model request limit reached. Upgrade to usage-based billing for more requests."
2798 }
2799 Plan::ZedProTrial => {
2800 "Model request limit reached. Upgrade to Zed Pro for more requests."
2801 }
2802 Plan::Free => "Model request limit reached. Upgrade to Zed Pro for more requests.",
2803 };
2804 let call_to_action = match plan {
2805 Plan::ZedPro => "Upgrade to usage-based billing",
2806 Plan::ZedProTrial => "Upgrade to Zed Pro",
2807 Plan::Free => "Upgrade to Zed Pro",
2808 };
2809
2810 v_flex()
2811 .gap_0p5()
2812 .child(
2813 h_flex()
2814 .gap_1p5()
2815 .items_center()
2816 .child(Icon::new(IconName::XCircle).color(Color::Error))
2817 .child(Label::new("Model Request Limit Reached").weight(FontWeight::MEDIUM)),
2818 )
2819 .child(
2820 div()
2821 .id("error-message")
2822 .max_h_24()
2823 .overflow_y_scroll()
2824 .child(Label::new(error_message)),
2825 )
2826 .child(
2827 h_flex()
2828 .justify_end()
2829 .mt_1()
2830 .gap_1()
2831 .child(self.create_copy_button(error_message))
2832 .child(
2833 Button::new("subscribe", call_to_action).on_click(cx.listener(
2834 |this, _, _, cx| {
2835 this.thread.update(cx, |this, _cx| {
2836 this.clear_last_error();
2837 });
2838
2839 cx.open_url(&zed_urls::account_url(cx));
2840 cx.notify();
2841 },
2842 )),
2843 )
2844 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2845 |this, _, _, cx| {
2846 this.thread.update(cx, |this, _cx| {
2847 this.clear_last_error();
2848 });
2849
2850 cx.notify();
2851 },
2852 ))),
2853 )
2854 .into_any()
2855 }
2856
2857 fn render_error_message(
2858 &self,
2859 header: SharedString,
2860 message: SharedString,
2861 cx: &mut Context<Self>,
2862 ) -> AnyElement {
2863 let message_with_header = format!("{}\n{}", header, message);
2864 v_flex()
2865 .gap_0p5()
2866 .child(
2867 h_flex()
2868 .gap_1p5()
2869 .items_center()
2870 .child(Icon::new(IconName::XCircle).color(Color::Error))
2871 .child(Label::new(header).weight(FontWeight::MEDIUM)),
2872 )
2873 .child(
2874 div()
2875 .id("error-message")
2876 .max_h_32()
2877 .overflow_y_scroll()
2878 .child(Label::new(message.clone())),
2879 )
2880 .child(
2881 h_flex()
2882 .justify_end()
2883 .mt_1()
2884 .gap_1()
2885 .child(self.create_copy_button(message_with_header))
2886 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2887 |this, _, _, cx| {
2888 this.thread.update(cx, |this, _cx| {
2889 this.clear_last_error();
2890 });
2891
2892 cx.notify();
2893 },
2894 ))),
2895 )
2896 .into_any()
2897 }
2898
2899 fn render_prompt_editor(
2900 &self,
2901 context_editor: &Entity<ContextEditor>,
2902 buffer_search_bar: &Entity<BufferSearchBar>,
2903 window: &mut Window,
2904 cx: &mut Context<Self>,
2905 ) -> Div {
2906 let mut registrar = buffer_search::DivRegistrar::new(
2907 |this, _, _cx| match &this.active_view {
2908 ActiveView::TextThread {
2909 buffer_search_bar, ..
2910 } => Some(buffer_search_bar.clone()),
2911 _ => None,
2912 },
2913 cx,
2914 );
2915 BufferSearchBar::register(&mut registrar);
2916 registrar
2917 .into_div()
2918 .size_full()
2919 .relative()
2920 .map(|parent| {
2921 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
2922 if buffer_search_bar.is_dismissed() {
2923 return parent;
2924 }
2925 parent.child(
2926 div()
2927 .p(DynamicSpacing::Base08.rems(cx))
2928 .border_b_1()
2929 .border_color(cx.theme().colors().border_variant)
2930 .bg(cx.theme().colors().editor_background)
2931 .child(buffer_search_bar.render(window, cx)),
2932 )
2933 })
2934 })
2935 .child(context_editor.clone())
2936 .child(self.render_drag_target(cx))
2937 }
2938
2939 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
2940 let is_local = self.project.read(cx).is_local();
2941 div()
2942 .invisible()
2943 .absolute()
2944 .top_0()
2945 .right_0()
2946 .bottom_0()
2947 .left_0()
2948 .bg(cx.theme().colors().drop_target_background)
2949 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
2950 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
2951 .when(is_local, |this| {
2952 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
2953 })
2954 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
2955 let item = tab.pane.read(cx).item_for_index(tab.ix);
2956 let project_paths = item
2957 .and_then(|item| item.project_path(cx))
2958 .into_iter()
2959 .collect::<Vec<_>>();
2960 this.handle_drop(project_paths, vec![], window, cx);
2961 }))
2962 .on_drop(
2963 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2964 let project_paths = selection
2965 .items()
2966 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
2967 .collect::<Vec<_>>();
2968 this.handle_drop(project_paths, vec![], window, cx);
2969 }),
2970 )
2971 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
2972 let tasks = paths
2973 .paths()
2974 .into_iter()
2975 .map(|path| {
2976 Workspace::project_path_for_path(this.project.clone(), &path, false, cx)
2977 })
2978 .collect::<Vec<_>>();
2979 cx.spawn_in(window, async move |this, cx| {
2980 let mut paths = vec![];
2981 let mut added_worktrees = vec![];
2982 let opened_paths = futures::future::join_all(tasks).await;
2983 for entry in opened_paths {
2984 if let Some((worktree, project_path)) = entry.log_err() {
2985 added_worktrees.push(worktree);
2986 paths.push(project_path);
2987 }
2988 }
2989 this.update_in(cx, |this, window, cx| {
2990 this.handle_drop(paths, added_worktrees, window, cx);
2991 })
2992 .ok();
2993 })
2994 .detach();
2995 }))
2996 }
2997
2998 fn handle_drop(
2999 &mut self,
3000 paths: Vec<ProjectPath>,
3001 added_worktrees: Vec<Entity<Worktree>>,
3002 window: &mut Window,
3003 cx: &mut Context<Self>,
3004 ) {
3005 match &self.active_view {
3006 ActiveView::Thread { .. } => {
3007 let context_store = self.thread.read(cx).context_store().clone();
3008 context_store.update(cx, move |context_store, cx| {
3009 let mut tasks = Vec::new();
3010 for project_path in &paths {
3011 tasks.push(context_store.add_file_from_path(
3012 project_path.clone(),
3013 false,
3014 cx,
3015 ));
3016 }
3017 cx.background_spawn(async move {
3018 futures::future::join_all(tasks).await;
3019 // Need to hold onto the worktrees until they have already been used when
3020 // opening the buffers.
3021 drop(added_worktrees);
3022 })
3023 .detach();
3024 });
3025 }
3026 ActiveView::TextThread { context_editor, .. } => {
3027 context_editor.update(cx, |context_editor, cx| {
3028 ContextEditor::insert_dragged_files(
3029 context_editor,
3030 paths,
3031 added_worktrees,
3032 window,
3033 cx,
3034 );
3035 });
3036 }
3037 ActiveView::History | ActiveView::Configuration => {}
3038 }
3039 }
3040
3041 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3042 let message = message.into();
3043 IconButton::new("copy", IconName::Copy)
3044 .on_click(move |_, _, cx| {
3045 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3046 })
3047 .tooltip(Tooltip::text("Copy Error Message"))
3048 }
3049
3050 fn key_context(&self) -> KeyContext {
3051 let mut key_context = KeyContext::new_with_defaults();
3052 key_context.add("AgentPanel");
3053 if matches!(self.active_view, ActiveView::TextThread { .. }) {
3054 key_context.add("prompt_editor");
3055 }
3056 key_context
3057 }
3058}
3059
3060impl Render for AgentPanel {
3061 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3062 // WARNING: Changes to this element hierarchy can have
3063 // non-obvious implications to the layout of children.
3064 //
3065 // If you need to change it, please confirm:
3066 // - The message editor expands (cmd-option-esc) correctly
3067 // - When expanded, the buttons at the bottom of the panel are displayed correctly
3068 // - Font size works as expected and can be changed with cmd-+/cmd-
3069 // - Scrolling in all views works as expected
3070 // - Files can be dropped into the panel
3071 let content = v_flex()
3072 .key_context(self.key_context())
3073 .justify_between()
3074 .size_full()
3075 .on_action(cx.listener(Self::cancel))
3076 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
3077 this.new_thread(action, window, cx);
3078 }))
3079 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
3080 this.open_history(window, cx);
3081 }))
3082 .on_action(cx.listener(|this, _: &OpenConfiguration, window, cx| {
3083 this.open_configuration(window, cx);
3084 }))
3085 .on_action(cx.listener(Self::open_active_thread_as_markdown))
3086 .on_action(cx.listener(Self::deploy_rules_library))
3087 .on_action(cx.listener(Self::open_agent_diff))
3088 .on_action(cx.listener(Self::go_back))
3089 .on_action(cx.listener(Self::toggle_navigation_menu))
3090 .on_action(cx.listener(Self::toggle_options_menu))
3091 .on_action(cx.listener(Self::increase_font_size))
3092 .on_action(cx.listener(Self::decrease_font_size))
3093 .on_action(cx.listener(Self::reset_font_size))
3094 .on_action(cx.listener(Self::toggle_zoom))
3095 .on_action(cx.listener(|this, _: &ContinueThread, window, cx| {
3096 this.continue_conversation(window, cx);
3097 }))
3098 .on_action(cx.listener(|this, _: &ContinueWithBurnMode, window, cx| {
3099 this.thread.update(cx, |active_thread, cx| {
3100 active_thread.thread().update(cx, |thread, _cx| {
3101 thread.set_completion_mode(CompletionMode::Burn);
3102 });
3103 });
3104 this.continue_conversation(window, cx);
3105 }))
3106 .on_action(cx.listener(Self::toggle_burn_mode))
3107 .child(self.render_toolbar(window, cx))
3108 .children(self.render_upsell(window, cx))
3109 .children(self.render_trial_end_upsell(window, cx))
3110 .map(|parent| match &self.active_view {
3111 ActiveView::Thread { .. } => parent
3112 .relative()
3113 .child(self.render_active_thread_or_empty_state(window, cx))
3114 .children(self.render_tool_use_limit_reached(window, cx))
3115 .child(h_flex().child(self.message_editor.clone()))
3116 .children(self.render_last_error(cx))
3117 .child(self.render_drag_target(cx)),
3118 ActiveView::History => parent.child(self.history.clone()),
3119 ActiveView::TextThread {
3120 context_editor,
3121 buffer_search_bar,
3122 ..
3123 } => parent.child(self.render_prompt_editor(
3124 context_editor,
3125 buffer_search_bar,
3126 window,
3127 cx,
3128 )),
3129 ActiveView::Configuration => parent.children(self.configuration.clone()),
3130 });
3131
3132 match self.active_view.which_font_size_used() {
3133 WhichFontSize::AgentFont => {
3134 WithRemSize::new(ThemeSettings::get_global(cx).agent_font_size(cx))
3135 .size_full()
3136 .child(content)
3137 .into_any()
3138 }
3139 _ => content.into_any(),
3140 }
3141 }
3142}
3143
3144struct PromptLibraryInlineAssist {
3145 workspace: WeakEntity<Workspace>,
3146}
3147
3148impl PromptLibraryInlineAssist {
3149 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
3150 Self { workspace }
3151 }
3152}
3153
3154impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
3155 fn assist(
3156 &self,
3157 prompt_editor: &Entity<Editor>,
3158 initial_prompt: Option<String>,
3159 window: &mut Window,
3160 cx: &mut Context<RulesLibrary>,
3161 ) {
3162 InlineAssistant::update_global(cx, |assistant, cx| {
3163 let Some(project) = self
3164 .workspace
3165 .upgrade()
3166 .map(|workspace| workspace.read(cx).project().downgrade())
3167 else {
3168 return;
3169 };
3170 let prompt_store = None;
3171 let thread_store = None;
3172 let text_thread_store = None;
3173 let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
3174 assistant.assist(
3175 &prompt_editor,
3176 self.workspace.clone(),
3177 context_store,
3178 project,
3179 prompt_store,
3180 thread_store,
3181 text_thread_store,
3182 initial_prompt,
3183 window,
3184 cx,
3185 )
3186 })
3187 }
3188
3189 fn focus_agent_panel(
3190 &self,
3191 workspace: &mut Workspace,
3192 window: &mut Window,
3193 cx: &mut Context<Workspace>,
3194 ) -> bool {
3195 workspace.focus_panel::<AgentPanel>(window, cx).is_some()
3196 }
3197}
3198
3199pub struct ConcreteAssistantPanelDelegate;
3200
3201impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
3202 fn active_context_editor(
3203 &self,
3204 workspace: &mut Workspace,
3205 _window: &mut Window,
3206 cx: &mut Context<Workspace>,
3207 ) -> Option<Entity<ContextEditor>> {
3208 let panel = workspace.panel::<AgentPanel>(cx)?;
3209 panel.read(cx).active_context_editor()
3210 }
3211
3212 fn open_saved_context(
3213 &self,
3214 workspace: &mut Workspace,
3215 path: Arc<Path>,
3216 window: &mut Window,
3217 cx: &mut Context<Workspace>,
3218 ) -> Task<Result<()>> {
3219 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3220 return Task::ready(Err(anyhow!("Agent panel not found")));
3221 };
3222
3223 panel.update(cx, |panel, cx| {
3224 panel.open_saved_prompt_editor(path, window, cx)
3225 })
3226 }
3227
3228 fn open_remote_context(
3229 &self,
3230 _workspace: &mut Workspace,
3231 _context_id: assistant_context_editor::ContextId,
3232 _window: &mut Window,
3233 _cx: &mut Context<Workspace>,
3234 ) -> Task<Result<Entity<ContextEditor>>> {
3235 Task::ready(Err(anyhow!("opening remote context not implemented")))
3236 }
3237
3238 fn quote_selection(
3239 &self,
3240 workspace: &mut Workspace,
3241 selection_ranges: Vec<Range<Anchor>>,
3242 buffer: Entity<MultiBuffer>,
3243 window: &mut Window,
3244 cx: &mut Context<Workspace>,
3245 ) {
3246 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3247 return;
3248 };
3249
3250 if !panel.focus_handle(cx).contains_focused(window, cx) {
3251 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
3252 }
3253
3254 panel.update(cx, |_, cx| {
3255 // Wait to create a new context until the workspace is no longer
3256 // being updated.
3257 cx.defer_in(window, move |panel, window, cx| {
3258 if panel.has_active_thread() {
3259 panel.message_editor.update(cx, |message_editor, cx| {
3260 message_editor.context_store().update(cx, |store, cx| {
3261 let buffer = buffer.read(cx);
3262 let selection_ranges = selection_ranges
3263 .into_iter()
3264 .flat_map(|range| {
3265 let (start_buffer, start) =
3266 buffer.text_anchor_for_position(range.start, cx)?;
3267 let (end_buffer, end) =
3268 buffer.text_anchor_for_position(range.end, cx)?;
3269 if start_buffer != end_buffer {
3270 return None;
3271 }
3272 Some((start_buffer, start..end))
3273 })
3274 .collect::<Vec<_>>();
3275
3276 for (buffer, range) in selection_ranges {
3277 store.add_selection(buffer, range, cx);
3278 }
3279 })
3280 })
3281 } else if let Some(context_editor) = panel.active_context_editor() {
3282 let snapshot = buffer.read(cx).snapshot(cx);
3283 let selection_ranges = selection_ranges
3284 .into_iter()
3285 .map(|range| range.to_point(&snapshot))
3286 .collect::<Vec<_>>();
3287
3288 context_editor.update(cx, |context_editor, cx| {
3289 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
3290 });
3291 }
3292 });
3293 });
3294 }
3295}
3296
3297struct Upsell;
3298
3299impl Dismissable for Upsell {
3300 const KEY: &'static str = "dismissed-trial-upsell";
3301}
3302
3303struct TrialEndUpsell;
3304
3305impl Dismissable for TrialEndUpsell {
3306 const KEY: &'static str = "dismissed-trial-end-upsell";
3307}