1use std::ops::{Not, Range};
2use std::path::Path;
3use std::rc::Rc;
4use std::sync::Arc;
5
6use acp_thread::AcpThread;
7use agent2::{DbThreadMetadata, HistoryEntry};
8use db::kvp::{Dismissable, KEY_VALUE_STORE};
9use project::agent_server_store::{
10 AgentServerCommand, AllAgentServersSettings, CLAUDE_CODE_NAME, GEMINI_NAME,
11};
12use serde::{Deserialize, Serialize};
13use settings::{
14 DefaultAgentView as DefaultView, LanguageModelProviderSetting, LanguageModelSelection,
15};
16use zed_actions::OpenBrowser;
17use zed_actions::agent::{OpenClaudeCodeOnboardingModal, ReauthenticateAgent};
18
19use crate::acp::{AcpThreadHistory, ThreadHistoryEvent};
20use crate::ui::{AcpOnboardingModal, ClaudeCodeOnboardingModal};
21use crate::{
22 AddContextServer, DeleteRecentlyOpenThread, Follow, InlineAssistant, NewTextThread, NewThread,
23 OpenActiveThreadAsMarkdown, OpenHistory, ResetTrialEndUpsell, ResetTrialUpsell,
24 ToggleNavigationMenu, ToggleNewThreadMenu, ToggleOptionsMenu,
25 acp::AcpThreadView,
26 agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},
27 slash_command::SlashCommandCompletionProvider,
28 text_thread_editor::{AgentPanelDelegate, TextThreadEditor, make_lsp_adapter_delegate},
29 ui::{AgentOnboardingModal, EndTrialUpsell},
30};
31use crate::{
32 ExternalAgent, NewExternalAgentThread, NewNativeAgentThreadFromSummary, placeholder_command,
33};
34use agent::{
35 context_store::ContextStore,
36 history_store::{HistoryEntryId, HistoryStore},
37 thread_store::{TextThreadStore, ThreadStore},
38};
39use agent_settings::AgentSettings;
40use ai_onboarding::AgentPanelOnboarding;
41use anyhow::{Result, anyhow};
42use assistant_context::{AssistantContext, ContextEvent, ContextSummary};
43use assistant_slash_command::SlashCommandWorkingSet;
44use assistant_tool::ToolWorkingSet;
45use client::{UserStore, zed_urls};
46use cloud_llm_client::{Plan, PlanV1, PlanV2, UsageLimit};
47use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
48use fs::Fs;
49use gpui::{
50 Action, AnyElement, App, AsyncWindowContext, Corner, DismissEvent, Entity, EventEmitter,
51 ExternalPaths, FocusHandle, Focusable, KeyContext, Pixels, Subscription, Task, UpdateGlobal,
52 WeakEntity, prelude::*,
53};
54use language::LanguageRegistry;
55use language_model::{ConfigurationError, LanguageModelRegistry};
56use project::{DisableAiSettings, Project, ProjectPath, Worktree};
57use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
58use rules_library::{RulesLibrary, open_rules_library};
59use search::{BufferSearchBar, buffer_search};
60use settings::{Settings, SettingsStore, update_settings_file};
61use theme::ThemeSettings;
62use ui::utils::WithRemSize;
63use ui::{
64 Callout, ContextMenu, ContextMenuEntry, KeyBinding, PopoverMenu, PopoverMenuHandle,
65 ProgressBar, Tab, Tooltip, prelude::*,
66};
67use util::ResultExt as _;
68use workspace::{
69 CollaboratorId, DraggedSelection, DraggedTab, ToggleZoom, ToolbarItemView, Workspace,
70 dock::{DockPosition, Panel, PanelEvent},
71};
72use zed_actions::{
73 DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,
74 agent::{OpenAcpOnboardingModal, OpenOnboardingModal, OpenSettings, ResetOnboarding},
75 assistant::{OpenRulesLibrary, ToggleFocus},
76};
77
78const AGENT_PANEL_KEY: &str = "agent_panel";
79
80#[derive(Serialize, Deserialize, Debug)]
81struct SerializedAgentPanel {
82 width: Option<Pixels>,
83 selected_agent: Option<AgentType>,
84}
85
86pub fn init(cx: &mut App) {
87 cx.observe_new(
88 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
89 workspace
90 .register_action(|workspace, action: &NewThread, window, cx| {
91 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
92 panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
93 workspace.focus_panel::<AgentPanel>(window, cx);
94 }
95 })
96 .register_action(
97 |workspace, action: &NewNativeAgentThreadFromSummary, window, cx| {
98 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
99 panel.update(cx, |panel, cx| {
100 panel.new_native_agent_thread_from_summary(action, window, cx)
101 });
102 workspace.focus_panel::<AgentPanel>(window, cx);
103 }
104 },
105 )
106 .register_action(|workspace, _: &OpenHistory, window, cx| {
107 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
108 workspace.focus_panel::<AgentPanel>(window, cx);
109 panel.update(cx, |panel, cx| panel.open_history(window, cx));
110 }
111 })
112 .register_action(|workspace, _: &OpenSettings, window, cx| {
113 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
114 workspace.focus_panel::<AgentPanel>(window, cx);
115 panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
116 }
117 })
118 .register_action(|workspace, _: &NewTextThread, window, cx| {
119 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
120 workspace.focus_panel::<AgentPanel>(window, cx);
121 panel.update(cx, |panel, cx| panel.new_prompt_editor(window, cx));
122 }
123 })
124 .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {
125 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
126 workspace.focus_panel::<AgentPanel>(window, cx);
127 panel.update(cx, |panel, cx| {
128 panel.external_thread(action.agent.clone(), None, None, window, cx)
129 });
130 }
131 })
132 .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
133 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
134 workspace.focus_panel::<AgentPanel>(window, cx);
135 panel.update(cx, |panel, cx| {
136 panel.deploy_rules_library(action, window, cx)
137 });
138 }
139 })
140 .register_action(|workspace, _: &Follow, window, cx| {
141 workspace.follow(CollaboratorId::Agent, window, cx);
142 })
143 .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {
144 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
145 workspace.focus_panel::<AgentPanel>(window, cx);
146 panel.update(cx, |panel, cx| {
147 panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);
148 });
149 }
150 })
151 .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
152 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
153 workspace.focus_panel::<AgentPanel>(window, cx);
154 panel.update(cx, |panel, cx| {
155 panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
156 });
157 }
158 })
159 .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {
160 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
161 workspace.focus_panel::<AgentPanel>(window, cx);
162 panel.update(cx, |panel, cx| {
163 panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);
164 });
165 }
166 })
167 .register_action(|workspace, _: &OpenOnboardingModal, window, cx| {
168 AgentOnboardingModal::toggle(workspace, window, cx)
169 })
170 .register_action(|workspace, _: &OpenAcpOnboardingModal, window, cx| {
171 AcpOnboardingModal::toggle(workspace, window, cx)
172 })
173 .register_action(|workspace, _: &OpenClaudeCodeOnboardingModal, window, cx| {
174 ClaudeCodeOnboardingModal::toggle(workspace, window, cx)
175 })
176 .register_action(|_workspace, _: &ResetOnboarding, window, cx| {
177 window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);
178 window.refresh();
179 })
180 .register_action(|_workspace, _: &ResetTrialUpsell, _window, cx| {
181 OnboardingUpsell::set_dismissed(false, cx);
182 })
183 .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {
184 TrialEndUpsell::set_dismissed(false, cx);
185 });
186 },
187 )
188 .detach();
189}
190
191enum ActiveView {
192 ExternalAgentThread {
193 thread_view: Entity<AcpThreadView>,
194 },
195 TextThread {
196 context_editor: Entity<TextThreadEditor>,
197 title_editor: Entity<Editor>,
198 buffer_search_bar: Entity<BufferSearchBar>,
199 _subscriptions: Vec<gpui::Subscription>,
200 },
201 History,
202 Configuration,
203}
204
205enum WhichFontSize {
206 AgentFont,
207 BufferFont,
208 None,
209}
210
211// TODO unify this with ExternalAgent
212#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
213pub enum AgentType {
214 #[default]
215 Zed,
216 TextThread,
217 Gemini,
218 ClaudeCode,
219 NativeAgent,
220 Custom {
221 name: SharedString,
222 command: AgentServerCommand,
223 },
224}
225
226impl AgentType {
227 fn label(&self) -> SharedString {
228 match self {
229 Self::Zed | Self::TextThread => "Zed Agent".into(),
230 Self::NativeAgent => "Agent 2".into(),
231 Self::Gemini => "Gemini CLI".into(),
232 Self::ClaudeCode => "Claude Code".into(),
233 Self::Custom { name, .. } => name.into(),
234 }
235 }
236
237 fn icon(&self) -> Option<IconName> {
238 match self {
239 Self::Zed | Self::NativeAgent | Self::TextThread => None,
240 Self::Gemini => Some(IconName::AiGemini),
241 Self::ClaudeCode => Some(IconName::AiClaude),
242 Self::Custom { .. } => Some(IconName::Terminal),
243 }
244 }
245}
246
247impl From<ExternalAgent> for AgentType {
248 fn from(value: ExternalAgent) -> Self {
249 match value {
250 ExternalAgent::Gemini => Self::Gemini,
251 ExternalAgent::ClaudeCode => Self::ClaudeCode,
252 ExternalAgent::Custom { name, command } => Self::Custom { name, command },
253 ExternalAgent::NativeAgent => Self::NativeAgent,
254 }
255 }
256}
257
258impl ActiveView {
259 pub fn which_font_size_used(&self) -> WhichFontSize {
260 match self {
261 ActiveView::ExternalAgentThread { .. } | ActiveView::History => {
262 WhichFontSize::AgentFont
263 }
264 ActiveView::TextThread { .. } => WhichFontSize::BufferFont,
265 ActiveView::Configuration => WhichFontSize::None,
266 }
267 }
268
269 pub fn native_agent(
270 fs: Arc<dyn Fs>,
271 prompt_store: Option<Entity<PromptStore>>,
272 acp_history_store: Entity<agent2::HistoryStore>,
273 project: Entity<Project>,
274 workspace: WeakEntity<Workspace>,
275 window: &mut Window,
276 cx: &mut App,
277 ) -> Self {
278 let thread_view = cx.new(|cx| {
279 crate::acp::AcpThreadView::new(
280 ExternalAgent::NativeAgent.server(fs, acp_history_store.clone()),
281 None,
282 None,
283 workspace,
284 project,
285 acp_history_store,
286 prompt_store,
287 window,
288 cx,
289 )
290 });
291
292 Self::ExternalAgentThread { thread_view }
293 }
294
295 pub fn prompt_editor(
296 context_editor: Entity<TextThreadEditor>,
297 history_store: Entity<HistoryStore>,
298 acp_history_store: Entity<agent2::HistoryStore>,
299 language_registry: Arc<LanguageRegistry>,
300 window: &mut Window,
301 cx: &mut App,
302 ) -> Self {
303 let title = context_editor.read(cx).title(cx).to_string();
304
305 let editor = cx.new(|cx| {
306 let mut editor = Editor::single_line(window, cx);
307 editor.set_text(title, window, cx);
308 editor
309 });
310
311 // This is a workaround for `editor.set_text` emitting a `BufferEdited` event, which would
312 // cause a custom summary to be set. The presence of this custom summary would cause
313 // summarization to not happen.
314 let mut suppress_first_edit = true;
315
316 let subscriptions = vec![
317 window.subscribe(&editor, cx, {
318 {
319 let context_editor = context_editor.clone();
320 move |editor, event, window, cx| match event {
321 EditorEvent::BufferEdited => {
322 if suppress_first_edit {
323 suppress_first_edit = false;
324 return;
325 }
326 let new_summary = editor.read(cx).text(cx);
327
328 context_editor.update(cx, |context_editor, cx| {
329 context_editor
330 .context()
331 .update(cx, |assistant_context, cx| {
332 assistant_context.set_custom_summary(new_summary, cx);
333 })
334 })
335 }
336 EditorEvent::Blurred => {
337 if editor.read(cx).text(cx).is_empty() {
338 let summary = context_editor
339 .read(cx)
340 .context()
341 .read(cx)
342 .summary()
343 .or_default();
344
345 editor.update(cx, |editor, cx| {
346 editor.set_text(summary, window, cx);
347 });
348 }
349 }
350 _ => {}
351 }
352 }
353 }),
354 window.subscribe(&context_editor.read(cx).context().clone(), cx, {
355 let editor = editor.clone();
356 move |assistant_context, event, window, cx| match event {
357 ContextEvent::SummaryGenerated => {
358 let summary = assistant_context.read(cx).summary().or_default();
359
360 editor.update(cx, |editor, cx| {
361 editor.set_text(summary, window, cx);
362 })
363 }
364 ContextEvent::PathChanged { old_path, new_path } => {
365 history_store.update(cx, |history_store, cx| {
366 if let Some(old_path) = old_path {
367 history_store
368 .replace_recently_opened_text_thread(old_path, new_path, cx);
369 } else {
370 history_store.push_recently_opened_entry(
371 HistoryEntryId::Context(new_path.clone()),
372 cx,
373 );
374 }
375 });
376
377 acp_history_store.update(cx, |history_store, cx| {
378 if let Some(old_path) = old_path {
379 history_store
380 .replace_recently_opened_text_thread(old_path, new_path, cx);
381 } else {
382 history_store.push_recently_opened_entry(
383 agent2::HistoryEntryId::TextThread(new_path.clone()),
384 cx,
385 );
386 }
387 });
388 }
389 _ => {}
390 }
391 }),
392 ];
393
394 let buffer_search_bar =
395 cx.new(|cx| BufferSearchBar::new(Some(language_registry), window, cx));
396 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
397 buffer_search_bar.set_active_pane_item(Some(&context_editor), window, cx)
398 });
399
400 Self::TextThread {
401 context_editor,
402 title_editor: editor,
403 buffer_search_bar,
404 _subscriptions: subscriptions,
405 }
406 }
407}
408
409pub struct AgentPanel {
410 workspace: WeakEntity<Workspace>,
411 user_store: Entity<UserStore>,
412 project: Entity<Project>,
413 fs: Arc<dyn Fs>,
414 language_registry: Arc<LanguageRegistry>,
415 thread_store: Entity<ThreadStore>,
416 acp_history: Entity<AcpThreadHistory>,
417 acp_history_store: Entity<agent2::HistoryStore>,
418 context_store: Entity<TextThreadStore>,
419 prompt_store: Option<Entity<PromptStore>>,
420 inline_assist_context_store: Entity<ContextStore>,
421 configuration: Option<Entity<AgentConfiguration>>,
422 configuration_subscription: Option<Subscription>,
423 active_view: ActiveView,
424 previous_view: Option<ActiveView>,
425 history_store: Entity<HistoryStore>,
426 new_thread_menu_handle: PopoverMenuHandle<ContextMenu>,
427 agent_panel_menu_handle: PopoverMenuHandle<ContextMenu>,
428 assistant_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
429 assistant_navigation_menu: Option<Entity<ContextMenu>>,
430 width: Option<Pixels>,
431 height: Option<Pixels>,
432 zoomed: bool,
433 pending_serialization: Option<Task<Result<()>>>,
434 onboarding: Entity<AgentPanelOnboarding>,
435 selected_agent: AgentType,
436}
437
438impl AgentPanel {
439 fn serialize(&mut self, cx: &mut Context<Self>) {
440 let width = self.width;
441 let selected_agent = self.selected_agent.clone();
442 self.pending_serialization = Some(cx.background_spawn(async move {
443 KEY_VALUE_STORE
444 .write_kvp(
445 AGENT_PANEL_KEY.into(),
446 serde_json::to_string(&SerializedAgentPanel {
447 width,
448 selected_agent: Some(selected_agent),
449 })?,
450 )
451 .await?;
452 anyhow::Ok(())
453 }));
454 }
455
456 pub fn load(
457 workspace: WeakEntity<Workspace>,
458 prompt_builder: Arc<PromptBuilder>,
459 mut cx: AsyncWindowContext,
460 ) -> Task<Result<Entity<Self>>> {
461 let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
462 cx.spawn(async move |cx| {
463 let prompt_store = match prompt_store {
464 Ok(prompt_store) => prompt_store.await.ok(),
465 Err(_) => None,
466 };
467 let tools = cx.new(|_| ToolWorkingSet::default())?;
468 let thread_store = workspace
469 .update(cx, |workspace, cx| {
470 let project = workspace.project().clone();
471 ThreadStore::load(
472 project,
473 tools.clone(),
474 prompt_store.clone(),
475 prompt_builder.clone(),
476 cx,
477 )
478 })?
479 .await?;
480
481 let slash_commands = Arc::new(SlashCommandWorkingSet::default());
482 let context_store = workspace
483 .update(cx, |workspace, cx| {
484 let project = workspace.project().clone();
485 assistant_context::ContextStore::new(
486 project,
487 prompt_builder.clone(),
488 slash_commands,
489 cx,
490 )
491 })?
492 .await?;
493
494 let serialized_panel = if let Some(panel) = cx
495 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(AGENT_PANEL_KEY) })
496 .await
497 .log_err()
498 .flatten()
499 {
500 serde_json::from_str::<SerializedAgentPanel>(&panel).log_err()
501 } else {
502 None
503 };
504
505 let panel = workspace.update_in(cx, |workspace, window, cx| {
506 let panel = cx.new(|cx| {
507 Self::new(
508 workspace,
509 thread_store,
510 context_store,
511 prompt_store,
512 window,
513 cx,
514 )
515 });
516 if let Some(serialized_panel) = serialized_panel {
517 panel.update(cx, |panel, cx| {
518 panel.width = serialized_panel.width.map(|w| w.round());
519 if let Some(selected_agent) = serialized_panel.selected_agent {
520 panel.selected_agent = selected_agent.clone();
521 panel.new_agent_thread(selected_agent, window, cx);
522 }
523 cx.notify();
524 });
525 } else {
526 panel.update(cx, |panel, cx| {
527 panel.new_agent_thread(AgentType::NativeAgent, window, cx);
528 });
529 }
530 panel
531 })?;
532
533 Ok(panel)
534 })
535 }
536
537 fn new(
538 workspace: &Workspace,
539 thread_store: Entity<ThreadStore>,
540 context_store: Entity<TextThreadStore>,
541 prompt_store: Option<Entity<PromptStore>>,
542 window: &mut Window,
543 cx: &mut Context<Self>,
544 ) -> Self {
545 let fs = workspace.app_state().fs.clone();
546 let user_store = workspace.app_state().user_store.clone();
547 let project = workspace.project();
548 let language_registry = project.read(cx).languages().clone();
549 let client = workspace.client().clone();
550 let workspace = workspace.weak_handle();
551
552 let inline_assist_context_store =
553 cx.new(|_cx| ContextStore::new(project.downgrade(), Some(thread_store.downgrade())));
554
555 let history_store = cx.new(|cx| HistoryStore::new(context_store.clone(), [], cx));
556
557 let acp_history_store = cx.new(|cx| agent2::HistoryStore::new(context_store.clone(), cx));
558 let acp_history = cx.new(|cx| AcpThreadHistory::new(acp_history_store.clone(), window, cx));
559 cx.subscribe_in(
560 &acp_history,
561 window,
562 |this, _, event, window, cx| match event {
563 ThreadHistoryEvent::Open(HistoryEntry::AcpThread(thread)) => {
564 this.external_thread(
565 Some(crate::ExternalAgent::NativeAgent),
566 Some(thread.clone()),
567 None,
568 window,
569 cx,
570 );
571 }
572 ThreadHistoryEvent::Open(HistoryEntry::TextThread(thread)) => {
573 this.open_saved_prompt_editor(thread.path.clone(), window, cx)
574 .detach_and_log_err(cx);
575 }
576 },
577 )
578 .detach();
579
580 cx.observe(&history_store, |_, _, cx| cx.notify()).detach();
581
582 let panel_type = AgentSettings::get_global(cx).default_view;
583 let active_view = match panel_type {
584 DefaultView::Thread => ActiveView::native_agent(
585 fs.clone(),
586 prompt_store.clone(),
587 acp_history_store.clone(),
588 project.clone(),
589 workspace.clone(),
590 window,
591 cx,
592 ),
593 DefaultView::TextThread => {
594 let context =
595 context_store.update(cx, |context_store, cx| context_store.create(cx));
596 let lsp_adapter_delegate = make_lsp_adapter_delegate(&project.clone(), cx).unwrap();
597 let context_editor = cx.new(|cx| {
598 let mut editor = TextThreadEditor::for_context(
599 context,
600 fs.clone(),
601 workspace.clone(),
602 project.clone(),
603 lsp_adapter_delegate,
604 window,
605 cx,
606 );
607 editor.insert_default_prompt(window, cx);
608 editor
609 });
610 ActiveView::prompt_editor(
611 context_editor,
612 history_store.clone(),
613 acp_history_store.clone(),
614 language_registry.clone(),
615 window,
616 cx,
617 )
618 }
619 };
620
621 let weak_panel = cx.entity().downgrade();
622
623 window.defer(cx, move |window, cx| {
624 let panel = weak_panel.clone();
625 let assistant_navigation_menu =
626 ContextMenu::build_persistent(window, cx, move |mut menu, _window, cx| {
627 if let Some(panel) = panel.upgrade() {
628 menu = Self::populate_recently_opened_menu_section(menu, panel, cx);
629 }
630 menu.action("View All", Box::new(OpenHistory))
631 .end_slot_action(DeleteRecentlyOpenThread.boxed_clone())
632 .fixed_width(px(320.).into())
633 .keep_open_on_confirm(false)
634 .key_context("NavigationMenu")
635 });
636 weak_panel
637 .update(cx, |panel, cx| {
638 cx.subscribe_in(
639 &assistant_navigation_menu,
640 window,
641 |_, menu, _: &DismissEvent, window, cx| {
642 menu.update(cx, |menu, _| {
643 menu.clear_selected();
644 });
645 cx.focus_self(window);
646 },
647 )
648 .detach();
649 panel.assistant_navigation_menu = Some(assistant_navigation_menu);
650 })
651 .ok();
652 });
653
654 let onboarding = cx.new(|cx| {
655 AgentPanelOnboarding::new(
656 user_store.clone(),
657 client,
658 |_window, cx| {
659 OnboardingUpsell::set_dismissed(true, cx);
660 },
661 cx,
662 )
663 });
664
665 Self {
666 active_view,
667 workspace,
668 user_store,
669 project: project.clone(),
670 fs: fs.clone(),
671 language_registry,
672 thread_store: thread_store.clone(),
673 context_store,
674 prompt_store,
675 configuration: None,
676 configuration_subscription: None,
677
678 inline_assist_context_store,
679 previous_view: None,
680 history_store: history_store.clone(),
681
682 new_thread_menu_handle: PopoverMenuHandle::default(),
683 agent_panel_menu_handle: PopoverMenuHandle::default(),
684 assistant_navigation_menu_handle: PopoverMenuHandle::default(),
685 assistant_navigation_menu: None,
686 width: None,
687 height: None,
688 zoomed: false,
689 pending_serialization: None,
690 onboarding,
691 acp_history,
692 acp_history_store,
693 selected_agent: AgentType::default(),
694 }
695 }
696
697 pub fn toggle_focus(
698 workspace: &mut Workspace,
699 _: &ToggleFocus,
700 window: &mut Window,
701 cx: &mut Context<Workspace>,
702 ) {
703 if workspace
704 .panel::<Self>(cx)
705 .is_some_and(|panel| panel.read(cx).enabled(cx))
706 && !DisableAiSettings::get_global(cx).disable_ai
707 {
708 workspace.toggle_panel_focus::<Self>(window, cx);
709 }
710 }
711
712 pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
713 &self.prompt_store
714 }
715
716 pub(crate) fn inline_assist_context_store(&self) -> &Entity<ContextStore> {
717 &self.inline_assist_context_store
718 }
719
720 pub(crate) fn thread_store(&self) -> &Entity<ThreadStore> {
721 &self.thread_store
722 }
723
724 pub(crate) fn text_thread_store(&self) -> &Entity<TextThreadStore> {
725 &self.context_store
726 }
727
728 fn active_thread_view(&self) -> Option<&Entity<AcpThreadView>> {
729 match &self.active_view {
730 ActiveView::ExternalAgentThread { thread_view, .. } => Some(thread_view),
731 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => None,
732 }
733 }
734
735 fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
736 self.new_agent_thread(AgentType::NativeAgent, window, cx);
737 }
738
739 fn new_native_agent_thread_from_summary(
740 &mut self,
741 action: &NewNativeAgentThreadFromSummary,
742 window: &mut Window,
743 cx: &mut Context<Self>,
744 ) {
745 let Some(thread) = self
746 .acp_history_store
747 .read(cx)
748 .thread_from_session_id(&action.from_session_id)
749 else {
750 return;
751 };
752
753 self.external_thread(
754 Some(ExternalAgent::NativeAgent),
755 None,
756 Some(thread.clone()),
757 window,
758 cx,
759 );
760 }
761
762 fn new_prompt_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
763 telemetry::event!("Agent Thread Started", agent = "zed-text");
764
765 let context = self
766 .context_store
767 .update(cx, |context_store, cx| context_store.create(cx));
768 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
769 .log_err()
770 .flatten();
771
772 let context_editor = cx.new(|cx| {
773 let mut editor = TextThreadEditor::for_context(
774 context,
775 self.fs.clone(),
776 self.workspace.clone(),
777 self.project.clone(),
778 lsp_adapter_delegate,
779 window,
780 cx,
781 );
782 editor.insert_default_prompt(window, cx);
783 editor
784 });
785
786 if self.selected_agent != AgentType::TextThread {
787 self.selected_agent = AgentType::TextThread;
788 self.serialize(cx);
789 }
790
791 self.set_active_view(
792 ActiveView::prompt_editor(
793 context_editor.clone(),
794 self.history_store.clone(),
795 self.acp_history_store.clone(),
796 self.language_registry.clone(),
797 window,
798 cx,
799 ),
800 window,
801 cx,
802 );
803 context_editor.focus_handle(cx).focus(window);
804 }
805
806 fn external_thread(
807 &mut self,
808 agent_choice: Option<crate::ExternalAgent>,
809 resume_thread: Option<DbThreadMetadata>,
810 summarize_thread: Option<DbThreadMetadata>,
811 window: &mut Window,
812 cx: &mut Context<Self>,
813 ) {
814 let workspace = self.workspace.clone();
815 let project = self.project.clone();
816 let fs = self.fs.clone();
817 let is_via_collab = self.project.read(cx).is_via_collab();
818
819 const LAST_USED_EXTERNAL_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
820
821 #[derive(Default, Serialize, Deserialize)]
822 struct LastUsedExternalAgent {
823 agent: crate::ExternalAgent,
824 }
825
826 let history = self.acp_history_store.clone();
827
828 cx.spawn_in(window, async move |this, cx| {
829 let ext_agent = match agent_choice {
830 Some(agent) => {
831 cx.background_spawn({
832 let agent = agent.clone();
833 async move {
834 if let Some(serialized) =
835 serde_json::to_string(&LastUsedExternalAgent { agent }).log_err()
836 {
837 KEY_VALUE_STORE
838 .write_kvp(LAST_USED_EXTERNAL_AGENT_KEY.to_string(), serialized)
839 .await
840 .log_err();
841 }
842 }
843 })
844 .detach();
845
846 agent
847 }
848 None => {
849 if is_via_collab {
850 ExternalAgent::NativeAgent
851 } else {
852 cx.background_spawn(async move {
853 KEY_VALUE_STORE.read_kvp(LAST_USED_EXTERNAL_AGENT_KEY)
854 })
855 .await
856 .log_err()
857 .flatten()
858 .and_then(|value| {
859 serde_json::from_str::<LastUsedExternalAgent>(&value).log_err()
860 })
861 .unwrap_or_default()
862 .agent
863 }
864 }
865 };
866
867 telemetry::event!("Agent Thread Started", agent = ext_agent.name());
868
869 let server = ext_agent.server(fs, history);
870
871 this.update_in(cx, |this, window, cx| {
872 let selected_agent = ext_agent.into();
873 if this.selected_agent != selected_agent {
874 this.selected_agent = selected_agent;
875 this.serialize(cx);
876 }
877
878 let thread_view = cx.new(|cx| {
879 crate::acp::AcpThreadView::new(
880 server,
881 resume_thread,
882 summarize_thread,
883 workspace.clone(),
884 project,
885 this.acp_history_store.clone(),
886 this.prompt_store.clone(),
887 window,
888 cx,
889 )
890 });
891
892 this.set_active_view(ActiveView::ExternalAgentThread { thread_view }, window, cx);
893 })
894 })
895 .detach_and_log_err(cx);
896 }
897
898 fn deploy_rules_library(
899 &mut self,
900 action: &OpenRulesLibrary,
901 _window: &mut Window,
902 cx: &mut Context<Self>,
903 ) {
904 open_rules_library(
905 self.language_registry.clone(),
906 Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
907 Rc::new(|| {
908 Rc::new(SlashCommandCompletionProvider::new(
909 Arc::new(SlashCommandWorkingSet::default()),
910 None,
911 None,
912 ))
913 }),
914 action
915 .prompt_to_select
916 .map(|uuid| UserPromptId(uuid).into()),
917 cx,
918 )
919 .detach_and_log_err(cx);
920 }
921
922 fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
923 if matches!(self.active_view, ActiveView::History) {
924 if let Some(previous_view) = self.previous_view.take() {
925 self.set_active_view(previous_view, window, cx);
926 }
927 } else {
928 self.thread_store
929 .update(cx, |thread_store, cx| thread_store.reload(cx))
930 .detach_and_log_err(cx);
931 self.set_active_view(ActiveView::History, window, cx);
932 }
933 cx.notify();
934 }
935
936 pub(crate) fn open_saved_prompt_editor(
937 &mut self,
938 path: Arc<Path>,
939 window: &mut Window,
940 cx: &mut Context<Self>,
941 ) -> Task<Result<()>> {
942 let context = self
943 .context_store
944 .update(cx, |store, cx| store.open_local_context(path, cx));
945 cx.spawn_in(window, async move |this, cx| {
946 let context = context.await?;
947 this.update_in(cx, |this, window, cx| {
948 this.open_prompt_editor(context, window, cx);
949 })
950 })
951 }
952
953 pub(crate) fn open_prompt_editor(
954 &mut self,
955 context: Entity<AssistantContext>,
956 window: &mut Window,
957 cx: &mut Context<Self>,
958 ) {
959 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project.clone(), cx)
960 .log_err()
961 .flatten();
962 let editor = cx.new(|cx| {
963 TextThreadEditor::for_context(
964 context,
965 self.fs.clone(),
966 self.workspace.clone(),
967 self.project.clone(),
968 lsp_adapter_delegate,
969 window,
970 cx,
971 )
972 });
973
974 if self.selected_agent != AgentType::TextThread {
975 self.selected_agent = AgentType::TextThread;
976 self.serialize(cx);
977 }
978
979 self.set_active_view(
980 ActiveView::prompt_editor(
981 editor,
982 self.history_store.clone(),
983 self.acp_history_store.clone(),
984 self.language_registry.clone(),
985 window,
986 cx,
987 ),
988 window,
989 cx,
990 );
991 }
992
993 pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
994 match self.active_view {
995 ActiveView::Configuration | ActiveView::History => {
996 if let Some(previous_view) = self.previous_view.take() {
997 self.active_view = previous_view;
998
999 match &self.active_view {
1000 ActiveView::ExternalAgentThread { thread_view } => {
1001 thread_view.focus_handle(cx).focus(window);
1002 }
1003 ActiveView::TextThread { context_editor, .. } => {
1004 context_editor.focus_handle(cx).focus(window);
1005 }
1006 ActiveView::History | ActiveView::Configuration => {}
1007 }
1008 }
1009 cx.notify();
1010 }
1011 _ => {}
1012 }
1013 }
1014
1015 pub fn toggle_navigation_menu(
1016 &mut self,
1017 _: &ToggleNavigationMenu,
1018 window: &mut Window,
1019 cx: &mut Context<Self>,
1020 ) {
1021 self.assistant_navigation_menu_handle.toggle(window, cx);
1022 }
1023
1024 pub fn toggle_options_menu(
1025 &mut self,
1026 _: &ToggleOptionsMenu,
1027 window: &mut Window,
1028 cx: &mut Context<Self>,
1029 ) {
1030 self.agent_panel_menu_handle.toggle(window, cx);
1031 }
1032
1033 pub fn toggle_new_thread_menu(
1034 &mut self,
1035 _: &ToggleNewThreadMenu,
1036 window: &mut Window,
1037 cx: &mut Context<Self>,
1038 ) {
1039 self.new_thread_menu_handle.toggle(window, cx);
1040 }
1041
1042 pub fn increase_font_size(
1043 &mut self,
1044 action: &IncreaseBufferFontSize,
1045 _: &mut Window,
1046 cx: &mut Context<Self>,
1047 ) {
1048 self.handle_font_size_action(action.persist, px(1.0), cx);
1049 }
1050
1051 pub fn decrease_font_size(
1052 &mut self,
1053 action: &DecreaseBufferFontSize,
1054 _: &mut Window,
1055 cx: &mut Context<Self>,
1056 ) {
1057 self.handle_font_size_action(action.persist, px(-1.0), cx);
1058 }
1059
1060 fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1061 match self.active_view.which_font_size_used() {
1062 WhichFontSize::AgentFont => {
1063 if persist {
1064 update_settings_file(self.fs.clone(), cx, move |settings, cx| {
1065 let agent_font_size =
1066 ThemeSettings::get_global(cx).agent_font_size(cx) + delta;
1067 let _ = settings
1068 .theme
1069 .agent_font_size
1070 .insert(theme::clamp_font_size(agent_font_size).into());
1071 });
1072 } else {
1073 theme::adjust_agent_font_size(cx, |size| size + delta);
1074 }
1075 }
1076 WhichFontSize::BufferFont => {
1077 // Prompt editor uses the buffer font size, so allow the action to propagate to the
1078 // default handler that changes that font size.
1079 cx.propagate();
1080 }
1081 WhichFontSize::None => {}
1082 }
1083 }
1084
1085 pub fn reset_font_size(
1086 &mut self,
1087 action: &ResetBufferFontSize,
1088 _: &mut Window,
1089 cx: &mut Context<Self>,
1090 ) {
1091 if action.persist {
1092 update_settings_file(self.fs.clone(), cx, move |settings, _| {
1093 settings.theme.agent_font_size = None;
1094 });
1095 } else {
1096 theme::reset_agent_font_size(cx);
1097 }
1098 }
1099
1100 pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1101 if self.zoomed {
1102 cx.emit(PanelEvent::ZoomOut);
1103 } else {
1104 if !self.focus_handle(cx).contains_focused(window, cx) {
1105 cx.focus_self(window);
1106 }
1107 cx.emit(PanelEvent::ZoomIn);
1108 }
1109 }
1110
1111 pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1112 let agent_server_store = self.project.read(cx).agent_server_store().clone();
1113 let context_server_store = self.project.read(cx).context_server_store();
1114 let tools = self.thread_store.read(cx).tools();
1115 let fs = self.fs.clone();
1116
1117 self.set_active_view(ActiveView::Configuration, window, cx);
1118 self.configuration = Some(cx.new(|cx| {
1119 AgentConfiguration::new(
1120 fs,
1121 agent_server_store,
1122 context_server_store,
1123 tools,
1124 self.language_registry.clone(),
1125 self.workspace.clone(),
1126 window,
1127 cx,
1128 )
1129 }));
1130
1131 if let Some(configuration) = self.configuration.as_ref() {
1132 self.configuration_subscription = Some(cx.subscribe_in(
1133 configuration,
1134 window,
1135 Self::handle_agent_configuration_event,
1136 ));
1137
1138 configuration.focus_handle(cx).focus(window);
1139 }
1140 }
1141
1142 pub(crate) fn open_active_thread_as_markdown(
1143 &mut self,
1144 _: &OpenActiveThreadAsMarkdown,
1145 window: &mut Window,
1146 cx: &mut Context<Self>,
1147 ) {
1148 let Some(workspace) = self.workspace.upgrade() else {
1149 return;
1150 };
1151
1152 match &self.active_view {
1153 ActiveView::ExternalAgentThread { thread_view } => {
1154 thread_view
1155 .update(cx, |thread_view, cx| {
1156 thread_view.open_thread_as_markdown(workspace, window, cx)
1157 })
1158 .detach_and_log_err(cx);
1159 }
1160 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {}
1161 }
1162 }
1163
1164 fn handle_agent_configuration_event(
1165 &mut self,
1166 _entity: &Entity<AgentConfiguration>,
1167 event: &AssistantConfigurationEvent,
1168 window: &mut Window,
1169 cx: &mut Context<Self>,
1170 ) {
1171 match event {
1172 AssistantConfigurationEvent::NewThread(provider) => {
1173 if LanguageModelRegistry::read_global(cx)
1174 .default_model()
1175 .is_none_or(|model| model.provider.id() != provider.id())
1176 && let Some(model) = provider.default_model(cx)
1177 {
1178 update_settings_file(self.fs.clone(), cx, move |settings, _| {
1179 let provider = model.provider_id().0.to_string();
1180 let model = model.id().0.to_string();
1181 settings
1182 .agent
1183 .get_or_insert_default()
1184 .set_model(LanguageModelSelection {
1185 provider: LanguageModelProviderSetting(provider),
1186 model,
1187 })
1188 });
1189 }
1190
1191 self.new_thread(&NewThread::default(), window, cx);
1192 if let Some((thread, model)) = self
1193 .active_native_agent_thread(cx)
1194 .zip(provider.default_model(cx))
1195 {
1196 thread.update(cx, |thread, cx| {
1197 thread.set_model(model, cx);
1198 });
1199 }
1200 }
1201 }
1202 }
1203
1204 pub(crate) fn active_agent_thread(&self, cx: &App) -> Option<Entity<AcpThread>> {
1205 match &self.active_view {
1206 ActiveView::ExternalAgentThread { thread_view, .. } => {
1207 thread_view.read(cx).thread().cloned()
1208 }
1209 _ => None,
1210 }
1211 }
1212
1213 pub(crate) fn active_native_agent_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
1214 match &self.active_view {
1215 ActiveView::ExternalAgentThread { thread_view, .. } => {
1216 thread_view.read(cx).as_native_thread(cx)
1217 }
1218 _ => None,
1219 }
1220 }
1221
1222 pub(crate) fn active_context_editor(&self) -> Option<Entity<TextThreadEditor>> {
1223 match &self.active_view {
1224 ActiveView::TextThread { context_editor, .. } => Some(context_editor.clone()),
1225 _ => None,
1226 }
1227 }
1228
1229 fn set_active_view(
1230 &mut self,
1231 new_view: ActiveView,
1232 window: &mut Window,
1233 cx: &mut Context<Self>,
1234 ) {
1235 let current_is_history = matches!(self.active_view, ActiveView::History);
1236 let new_is_history = matches!(new_view, ActiveView::History);
1237
1238 let current_is_config = matches!(self.active_view, ActiveView::Configuration);
1239 let new_is_config = matches!(new_view, ActiveView::Configuration);
1240
1241 let current_is_special = current_is_history || current_is_config;
1242 let new_is_special = new_is_history || new_is_config;
1243
1244 match &new_view {
1245 ActiveView::TextThread { context_editor, .. } => {
1246 self.history_store.update(cx, |store, cx| {
1247 if let Some(path) = context_editor.read(cx).context().read(cx).path() {
1248 store.push_recently_opened_entry(HistoryEntryId::Context(path.clone()), cx)
1249 }
1250 });
1251 self.acp_history_store.update(cx, |store, cx| {
1252 if let Some(path) = context_editor.read(cx).context().read(cx).path() {
1253 store.push_recently_opened_entry(
1254 agent2::HistoryEntryId::TextThread(path.clone()),
1255 cx,
1256 )
1257 }
1258 })
1259 }
1260 ActiveView::ExternalAgentThread { .. } => {}
1261 ActiveView::History | ActiveView::Configuration => {}
1262 }
1263
1264 if current_is_special && !new_is_special {
1265 self.active_view = new_view;
1266 } else if !current_is_special && new_is_special {
1267 self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
1268 } else {
1269 if !new_is_special {
1270 self.previous_view = None;
1271 }
1272 self.active_view = new_view;
1273 }
1274
1275 self.focus_handle(cx).focus(window);
1276 }
1277
1278 fn populate_recently_opened_menu_section(
1279 mut menu: ContextMenu,
1280 panel: Entity<Self>,
1281 cx: &mut Context<ContextMenu>,
1282 ) -> ContextMenu {
1283 let entries = panel
1284 .read(cx)
1285 .acp_history_store
1286 .read(cx)
1287 .recently_opened_entries(cx);
1288
1289 if entries.is_empty() {
1290 return menu;
1291 }
1292
1293 menu = menu.header("Recently Opened");
1294
1295 for entry in entries {
1296 let title = entry.title().clone();
1297
1298 menu = menu.entry_with_end_slot_on_hover(
1299 title,
1300 None,
1301 {
1302 let panel = panel.downgrade();
1303 let entry = entry.clone();
1304 move |window, cx| {
1305 let entry = entry.clone();
1306 panel
1307 .update(cx, move |this, cx| match &entry {
1308 agent2::HistoryEntry::AcpThread(entry) => this.external_thread(
1309 Some(ExternalAgent::NativeAgent),
1310 Some(entry.clone()),
1311 None,
1312 window,
1313 cx,
1314 ),
1315 agent2::HistoryEntry::TextThread(entry) => this
1316 .open_saved_prompt_editor(entry.path.clone(), window, cx)
1317 .detach_and_log_err(cx),
1318 })
1319 .ok();
1320 }
1321 },
1322 IconName::Close,
1323 "Close Entry".into(),
1324 {
1325 let panel = panel.downgrade();
1326 let id = entry.id();
1327 move |_window, cx| {
1328 panel
1329 .update(cx, |this, cx| {
1330 this.acp_history_store.update(cx, |history_store, cx| {
1331 history_store.remove_recently_opened_entry(&id, cx);
1332 });
1333 })
1334 .ok();
1335 }
1336 },
1337 );
1338 }
1339
1340 menu = menu.separator();
1341
1342 menu
1343 }
1344
1345 pub fn selected_agent(&self) -> AgentType {
1346 self.selected_agent.clone()
1347 }
1348
1349 pub fn new_agent_thread(
1350 &mut self,
1351 agent: AgentType,
1352 window: &mut Window,
1353 cx: &mut Context<Self>,
1354 ) {
1355 match agent {
1356 AgentType::Zed => {
1357 window.dispatch_action(
1358 NewThread {
1359 from_thread_id: None,
1360 }
1361 .boxed_clone(),
1362 cx,
1363 );
1364 }
1365 AgentType::TextThread => {
1366 window.dispatch_action(NewTextThread.boxed_clone(), cx);
1367 }
1368 AgentType::NativeAgent => self.external_thread(
1369 Some(crate::ExternalAgent::NativeAgent),
1370 None,
1371 None,
1372 window,
1373 cx,
1374 ),
1375 AgentType::Gemini => {
1376 self.external_thread(Some(crate::ExternalAgent::Gemini), None, None, window, cx)
1377 }
1378 AgentType::ClaudeCode => {
1379 self.selected_agent = AgentType::ClaudeCode;
1380 self.serialize(cx);
1381 self.external_thread(
1382 Some(crate::ExternalAgent::ClaudeCode),
1383 None,
1384 None,
1385 window,
1386 cx,
1387 )
1388 }
1389 AgentType::Custom { name, command } => self.external_thread(
1390 Some(crate::ExternalAgent::Custom { name, command }),
1391 None,
1392 None,
1393 window,
1394 cx,
1395 ),
1396 }
1397 }
1398
1399 pub fn load_agent_thread(
1400 &mut self,
1401 thread: DbThreadMetadata,
1402 window: &mut Window,
1403 cx: &mut Context<Self>,
1404 ) {
1405 self.external_thread(
1406 Some(ExternalAgent::NativeAgent),
1407 Some(thread),
1408 None,
1409 window,
1410 cx,
1411 );
1412 }
1413}
1414
1415impl Focusable for AgentPanel {
1416 fn focus_handle(&self, cx: &App) -> FocusHandle {
1417 match &self.active_view {
1418 ActiveView::ExternalAgentThread { thread_view, .. } => thread_view.focus_handle(cx),
1419 ActiveView::History => self.acp_history.focus_handle(cx),
1420 ActiveView::TextThread { context_editor, .. } => context_editor.focus_handle(cx),
1421 ActiveView::Configuration => {
1422 if let Some(configuration) = self.configuration.as_ref() {
1423 configuration.focus_handle(cx)
1424 } else {
1425 cx.focus_handle()
1426 }
1427 }
1428 }
1429 }
1430}
1431
1432fn agent_panel_dock_position(cx: &App) -> DockPosition {
1433 AgentSettings::get_global(cx).dock.into()
1434}
1435
1436impl EventEmitter<PanelEvent> for AgentPanel {}
1437
1438impl Panel for AgentPanel {
1439 fn persistent_name() -> &'static str {
1440 "AgentPanel"
1441 }
1442
1443 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1444 agent_panel_dock_position(cx)
1445 }
1446
1447 fn position_is_valid(&self, position: DockPosition) -> bool {
1448 position != DockPosition::Bottom
1449 }
1450
1451 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1452 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1453 settings
1454 .agent
1455 .get_or_insert_default()
1456 .set_dock(position.into());
1457 });
1458 }
1459
1460 fn size(&self, window: &Window, cx: &App) -> Pixels {
1461 let settings = AgentSettings::get_global(cx);
1462 match self.position(window, cx) {
1463 DockPosition::Left | DockPosition::Right => {
1464 self.width.unwrap_or(settings.default_width)
1465 }
1466 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1467 }
1468 }
1469
1470 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1471 match self.position(window, cx) {
1472 DockPosition::Left | DockPosition::Right => self.width = size,
1473 DockPosition::Bottom => self.height = size,
1474 }
1475 self.serialize(cx);
1476 cx.notify();
1477 }
1478
1479 fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
1480
1481 fn remote_id() -> Option<proto::PanelId> {
1482 Some(proto::PanelId::AssistantPanel)
1483 }
1484
1485 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1486 (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
1487 }
1488
1489 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1490 Some("Agent Panel")
1491 }
1492
1493 fn toggle_action(&self) -> Box<dyn Action> {
1494 Box::new(ToggleFocus)
1495 }
1496
1497 fn activation_priority(&self) -> u32 {
1498 3
1499 }
1500
1501 fn enabled(&self, cx: &App) -> bool {
1502 DisableAiSettings::get_global(cx).disable_ai.not() && AgentSettings::get_global(cx).enabled
1503 }
1504
1505 fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1506 self.zoomed
1507 }
1508
1509 fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1510 self.zoomed = zoomed;
1511 cx.notify();
1512 }
1513}
1514
1515impl AgentPanel {
1516 fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
1517 const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
1518
1519 let content = match &self.active_view {
1520 ActiveView::ExternalAgentThread { thread_view } => {
1521 if let Some(title_editor) = thread_view.read(cx).title_editor() {
1522 div()
1523 .w_full()
1524 .on_action({
1525 let thread_view = thread_view.downgrade();
1526 move |_: &menu::Confirm, window, cx| {
1527 if let Some(thread_view) = thread_view.upgrade() {
1528 thread_view.focus_handle(cx).focus(window);
1529 }
1530 }
1531 })
1532 .on_action({
1533 let thread_view = thread_view.downgrade();
1534 move |_: &editor::actions::Cancel, window, cx| {
1535 if let Some(thread_view) = thread_view.upgrade() {
1536 thread_view.focus_handle(cx).focus(window);
1537 }
1538 }
1539 })
1540 .child(title_editor)
1541 .into_any_element()
1542 } else {
1543 Label::new(thread_view.read(cx).title(cx))
1544 .color(Color::Muted)
1545 .truncate()
1546 .into_any_element()
1547 }
1548 }
1549 ActiveView::TextThread {
1550 title_editor,
1551 context_editor,
1552 ..
1553 } => {
1554 let summary = context_editor.read(cx).context().read(cx).summary();
1555
1556 match summary {
1557 ContextSummary::Pending => Label::new(ContextSummary::DEFAULT)
1558 .color(Color::Muted)
1559 .truncate()
1560 .into_any_element(),
1561 ContextSummary::Content(summary) => {
1562 if summary.done {
1563 div()
1564 .w_full()
1565 .child(title_editor.clone())
1566 .into_any_element()
1567 } else {
1568 Label::new(LOADING_SUMMARY_PLACEHOLDER)
1569 .truncate()
1570 .color(Color::Muted)
1571 .into_any_element()
1572 }
1573 }
1574 ContextSummary::Error => h_flex()
1575 .w_full()
1576 .child(title_editor.clone())
1577 .child(
1578 IconButton::new("retry-summary-generation", IconName::RotateCcw)
1579 .icon_size(IconSize::Small)
1580 .on_click({
1581 let context_editor = context_editor.clone();
1582 move |_, _window, cx| {
1583 context_editor.update(cx, |context_editor, cx| {
1584 context_editor.regenerate_summary(cx);
1585 });
1586 }
1587 })
1588 .tooltip(move |_window, cx| {
1589 cx.new(|_| {
1590 Tooltip::new("Failed to generate title")
1591 .meta("Click to try again")
1592 })
1593 .into()
1594 }),
1595 )
1596 .into_any_element(),
1597 }
1598 }
1599 ActiveView::History => Label::new("History").truncate().into_any_element(),
1600 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
1601 };
1602
1603 h_flex()
1604 .key_context("TitleEditor")
1605 .id("TitleEditor")
1606 .flex_grow()
1607 .w_full()
1608 .max_w_full()
1609 .overflow_x_scroll()
1610 .child(content)
1611 .into_any()
1612 }
1613
1614 fn render_panel_options_menu(
1615 &self,
1616 window: &mut Window,
1617 cx: &mut Context<Self>,
1618 ) -> impl IntoElement {
1619 let user_store = self.user_store.read(cx);
1620 let usage = user_store.model_request_usage();
1621 let account_url = zed_urls::account_url(cx);
1622
1623 let focus_handle = self.focus_handle(cx);
1624
1625 let full_screen_label = if self.is_zoomed(window, cx) {
1626 "Disable Full Screen"
1627 } else {
1628 "Enable Full Screen"
1629 };
1630
1631 let selected_agent = self.selected_agent.clone();
1632
1633 PopoverMenu::new("agent-options-menu")
1634 .trigger_with_tooltip(
1635 IconButton::new("agent-options-menu", IconName::Ellipsis)
1636 .icon_size(IconSize::Small),
1637 {
1638 let focus_handle = focus_handle.clone();
1639 move |window, cx| {
1640 Tooltip::for_action_in(
1641 "Toggle Agent Menu",
1642 &ToggleOptionsMenu,
1643 &focus_handle,
1644 window,
1645 cx,
1646 )
1647 }
1648 },
1649 )
1650 .anchor(Corner::TopRight)
1651 .with_handle(self.agent_panel_menu_handle.clone())
1652 .menu({
1653 move |window, cx| {
1654 Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
1655 menu = menu.context(focus_handle.clone());
1656 if let Some(usage) = usage {
1657 menu = menu
1658 .header_with_link("Prompt Usage", "Manage", account_url.clone())
1659 .custom_entry(
1660 move |_window, cx| {
1661 let used_percentage = match usage.limit {
1662 UsageLimit::Limited(limit) => {
1663 Some((usage.amount as f32 / limit as f32) * 100.)
1664 }
1665 UsageLimit::Unlimited => None,
1666 };
1667
1668 h_flex()
1669 .flex_1()
1670 .gap_1p5()
1671 .children(used_percentage.map(|percent| {
1672 ProgressBar::new("usage", percent, 100., cx)
1673 }))
1674 .child(
1675 Label::new(match usage.limit {
1676 UsageLimit::Limited(limit) => {
1677 format!("{} / {limit}", usage.amount)
1678 }
1679 UsageLimit::Unlimited => {
1680 format!("{} / ∞", usage.amount)
1681 }
1682 })
1683 .size(LabelSize::Small)
1684 .color(Color::Muted),
1685 )
1686 .into_any_element()
1687 },
1688 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
1689 )
1690 .separator()
1691 }
1692
1693 menu = menu
1694 .header("MCP Servers")
1695 .action(
1696 "View Server Extensions",
1697 Box::new(zed_actions::Extensions {
1698 category_filter: Some(
1699 zed_actions::ExtensionCategoryFilter::ContextServers,
1700 ),
1701 id: None,
1702 }),
1703 )
1704 .action("Add Custom Server…", Box::new(AddContextServer))
1705 .separator();
1706
1707 menu = menu
1708 .action("Rules…", Box::new(OpenRulesLibrary::default()))
1709 .action("Settings", Box::new(OpenSettings))
1710 .separator()
1711 .action(full_screen_label, Box::new(ToggleZoom));
1712
1713 if selected_agent == AgentType::Gemini {
1714 menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
1715 }
1716
1717 menu
1718 }))
1719 }
1720 })
1721 }
1722
1723 fn render_recent_entries_menu(
1724 &self,
1725 icon: IconName,
1726 corner: Corner,
1727 cx: &mut Context<Self>,
1728 ) -> impl IntoElement {
1729 let focus_handle = self.focus_handle(cx);
1730
1731 PopoverMenu::new("agent-nav-menu")
1732 .trigger_with_tooltip(
1733 IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
1734 {
1735 move |window, cx| {
1736 Tooltip::for_action_in(
1737 "Toggle Recent Threads",
1738 &ToggleNavigationMenu,
1739 &focus_handle,
1740 window,
1741 cx,
1742 )
1743 }
1744 },
1745 )
1746 .anchor(corner)
1747 .with_handle(self.assistant_navigation_menu_handle.clone())
1748 .menu({
1749 let menu = self.assistant_navigation_menu.clone();
1750 move |window, cx| {
1751 telemetry::event!("View Thread History Clicked");
1752
1753 if let Some(menu) = menu.as_ref() {
1754 menu.update(cx, |_, cx| {
1755 cx.defer_in(window, |menu, window, cx| {
1756 menu.rebuild(window, cx);
1757 });
1758 })
1759 }
1760 menu.clone()
1761 }
1762 })
1763 }
1764
1765 fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
1766 let focus_handle = self.focus_handle(cx);
1767
1768 IconButton::new("go-back", IconName::ArrowLeft)
1769 .icon_size(IconSize::Small)
1770 .on_click(cx.listener(|this, _, window, cx| {
1771 this.go_back(&workspace::GoBack, window, cx);
1772 }))
1773 .tooltip({
1774 move |window, cx| {
1775 Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, window, cx)
1776 }
1777 })
1778 }
1779
1780 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1781 let agent_server_store = self.project.read(cx).agent_server_store().clone();
1782 let focus_handle = self.focus_handle(cx);
1783
1784 let active_thread = match &self.active_view {
1785 ActiveView::ExternalAgentThread { thread_view } => {
1786 thread_view.read(cx).as_native_thread(cx)
1787 }
1788 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => None,
1789 };
1790
1791 let new_thread_menu = PopoverMenu::new("new_thread_menu")
1792 .trigger_with_tooltip(
1793 IconButton::new("new_thread_menu_btn", IconName::Plus).icon_size(IconSize::Small),
1794 {
1795 let focus_handle = focus_handle.clone();
1796 move |window, cx| {
1797 Tooltip::for_action_in(
1798 "New…",
1799 &ToggleNewThreadMenu,
1800 &focus_handle,
1801 window,
1802 cx,
1803 )
1804 }
1805 },
1806 )
1807 .anchor(Corner::TopRight)
1808 .with_handle(self.new_thread_menu_handle.clone())
1809 .menu({
1810 let workspace = self.workspace.clone();
1811 let is_via_collab = workspace
1812 .update(cx, |workspace, cx| {
1813 workspace.project().read(cx).is_via_collab()
1814 })
1815 .unwrap_or_default();
1816
1817 move |window, cx| {
1818 telemetry::event!("New Thread Clicked");
1819
1820 let active_thread = active_thread.clone();
1821 Some(ContextMenu::build(window, cx, |menu, _window, cx| {
1822 menu
1823 .context(focus_handle.clone())
1824 .header("Zed Agent")
1825 .when_some(active_thread, |this, active_thread| {
1826 let thread = active_thread.read(cx);
1827
1828 if !thread.is_empty() {
1829 let session_id = thread.id().clone();
1830 this.item(
1831 ContextMenuEntry::new("New From Summary")
1832 .icon(IconName::ThreadFromSummary)
1833 .icon_color(Color::Muted)
1834 .handler(move |window, cx| {
1835 window.dispatch_action(
1836 Box::new(NewNativeAgentThreadFromSummary {
1837 from_session_id: session_id.clone(),
1838 }),
1839 cx,
1840 );
1841 }),
1842 )
1843 } else {
1844 this
1845 }
1846 })
1847 .item(
1848 ContextMenuEntry::new("New Thread")
1849 .action(NewThread::default().boxed_clone())
1850 .icon(IconName::Thread)
1851 .icon_color(Color::Muted)
1852 .handler({
1853 let workspace = workspace.clone();
1854 move |window, cx| {
1855 if let Some(workspace) = workspace.upgrade() {
1856 workspace.update(cx, |workspace, cx| {
1857 if let Some(panel) =
1858 workspace.panel::<AgentPanel>(cx)
1859 {
1860 panel.update(cx, |panel, cx| {
1861 panel.new_agent_thread(
1862 AgentType::NativeAgent,
1863 window,
1864 cx,
1865 );
1866 });
1867 }
1868 });
1869 }
1870 }
1871 }),
1872 )
1873 .item(
1874 ContextMenuEntry::new("New Text Thread")
1875 .icon(IconName::TextThread)
1876 .icon_color(Color::Muted)
1877 .action(NewTextThread.boxed_clone())
1878 .handler({
1879 let workspace = workspace.clone();
1880 move |window, cx| {
1881 if let Some(workspace) = workspace.upgrade() {
1882 workspace.update(cx, |workspace, cx| {
1883 if let Some(panel) =
1884 workspace.panel::<AgentPanel>(cx)
1885 {
1886 panel.update(cx, |panel, cx| {
1887 panel.new_agent_thread(
1888 AgentType::TextThread,
1889 window,
1890 cx,
1891 );
1892 });
1893 }
1894 });
1895 }
1896 }
1897 }),
1898 )
1899 .separator()
1900 .header("External Agents")
1901 .item(
1902 ContextMenuEntry::new("New Gemini CLI Thread")
1903 .icon(IconName::AiGemini)
1904 .icon_color(Color::Muted)
1905 .disabled(is_via_collab)
1906 .handler({
1907 let workspace = workspace.clone();
1908 move |window, cx| {
1909 if let Some(workspace) = workspace.upgrade() {
1910 workspace.update(cx, |workspace, cx| {
1911 if let Some(panel) =
1912 workspace.panel::<AgentPanel>(cx)
1913 {
1914 panel.update(cx, |panel, cx| {
1915 panel.new_agent_thread(
1916 AgentType::Gemini,
1917 window,
1918 cx,
1919 );
1920 });
1921 }
1922 });
1923 }
1924 }
1925 }),
1926 )
1927 .item(
1928 ContextMenuEntry::new("New Claude Code Thread")
1929 .icon(IconName::AiClaude)
1930 .disabled(is_via_collab)
1931 .icon_color(Color::Muted)
1932 .handler({
1933 let workspace = workspace.clone();
1934 move |window, cx| {
1935 if let Some(workspace) = workspace.upgrade() {
1936 workspace.update(cx, |workspace, cx| {
1937 if let Some(panel) =
1938 workspace.panel::<AgentPanel>(cx)
1939 {
1940 panel.update(cx, |panel, cx| {
1941 panel.new_agent_thread(
1942 AgentType::ClaudeCode,
1943 window,
1944 cx,
1945 );
1946 });
1947 }
1948 });
1949 }
1950 }
1951 }),
1952 )
1953 .map(|mut menu| {
1954 let agent_names = agent_server_store
1955 .read(cx)
1956 .external_agents()
1957 .filter(|name| {
1958 name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME
1959 })
1960 .cloned()
1961 .collect::<Vec<_>>();
1962 let custom_settings = cx.global::<SettingsStore>().get::<AllAgentServersSettings>(None).custom.clone();
1963 for agent_name in agent_names {
1964 menu = menu.item(
1965 ContextMenuEntry::new(format!("New {} Thread", agent_name))
1966 .icon(IconName::Terminal)
1967 .icon_color(Color::Muted)
1968 .disabled(is_via_collab)
1969 .handler({
1970 let workspace = workspace.clone();
1971 let agent_name = agent_name.clone();
1972 let custom_settings = custom_settings.clone();
1973 move |window, cx| {
1974 if let Some(workspace) = workspace.upgrade() {
1975 workspace.update(cx, |workspace, cx| {
1976 if let Some(panel) =
1977 workspace.panel::<AgentPanel>(cx)
1978 {
1979 panel.update(cx, |panel, cx| {
1980 panel.new_agent_thread(
1981 AgentType::Custom {
1982 name: agent_name.clone().into(),
1983 command: custom_settings
1984 .get(&agent_name.0)
1985 .map(|settings| {
1986 settings.command.clone()
1987 })
1988 .unwrap_or(placeholder_command()),
1989 },
1990 window,
1991 cx,
1992 );
1993 });
1994 }
1995 });
1996 }
1997 }
1998 }),
1999 );
2000 }
2001
2002 menu
2003 })
2004 .separator().link(
2005 "Add Other Agents",
2006 OpenBrowser {
2007 url: zed_urls::external_agents_docs(cx),
2008 }
2009 .boxed_clone(),
2010 )
2011 }))
2012 }
2013 });
2014
2015 let selected_agent_label = self.selected_agent.label();
2016 let selected_agent = div()
2017 .id("selected_agent_icon")
2018 .when_some(self.selected_agent.icon(), |this, icon| {
2019 this.px(DynamicSpacing::Base02.rems(cx))
2020 .child(Icon::new(icon).color(Color::Muted))
2021 .tooltip(move |window, cx| {
2022 Tooltip::with_meta(
2023 selected_agent_label.clone(),
2024 None,
2025 "Selected Agent",
2026 window,
2027 cx,
2028 )
2029 })
2030 })
2031 .into_any_element();
2032
2033 h_flex()
2034 .id("agent-panel-toolbar")
2035 .h(Tab::container_height(cx))
2036 .max_w_full()
2037 .flex_none()
2038 .justify_between()
2039 .gap_2()
2040 .bg(cx.theme().colors().tab_bar_background)
2041 .border_b_1()
2042 .border_color(cx.theme().colors().border)
2043 .child(
2044 h_flex()
2045 .size_full()
2046 .gap(DynamicSpacing::Base04.rems(cx))
2047 .pl(DynamicSpacing::Base04.rems(cx))
2048 .child(match &self.active_view {
2049 ActiveView::History | ActiveView::Configuration => {
2050 self.render_toolbar_back_button(cx).into_any_element()
2051 }
2052 _ => selected_agent.into_any_element(),
2053 })
2054 .child(self.render_title_view(window, cx)),
2055 )
2056 .child(
2057 h_flex()
2058 .flex_none()
2059 .gap(DynamicSpacing::Base02.rems(cx))
2060 .pl(DynamicSpacing::Base04.rems(cx))
2061 .pr(DynamicSpacing::Base06.rems(cx))
2062 .child(new_thread_menu)
2063 .child(self.render_recent_entries_menu(
2064 IconName::MenuAltTemp,
2065 Corner::TopRight,
2066 cx,
2067 ))
2068 .child(self.render_panel_options_menu(window, cx)),
2069 )
2070 }
2071
2072 fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
2073 if TrialEndUpsell::dismissed() {
2074 return false;
2075 }
2076
2077 match &self.active_view {
2078 ActiveView::TextThread { .. } => {
2079 if LanguageModelRegistry::global(cx)
2080 .read(cx)
2081 .default_model()
2082 .is_some_and(|model| {
2083 model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2084 })
2085 {
2086 return false;
2087 }
2088 }
2089 ActiveView::ExternalAgentThread { .. }
2090 | ActiveView::History
2091 | ActiveView::Configuration => return false,
2092 }
2093
2094 let plan = self.user_store.read(cx).plan();
2095 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2096
2097 matches!(
2098 plan,
2099 Some(Plan::V1(PlanV1::ZedFree) | Plan::V2(PlanV2::ZedFree))
2100 ) && has_previous_trial
2101 }
2102
2103 fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
2104 if OnboardingUpsell::dismissed() {
2105 return false;
2106 }
2107
2108 let user_store = self.user_store.read(cx);
2109
2110 if user_store
2111 .plan()
2112 .is_some_and(|plan| matches!(plan, Plan::V1(PlanV1::ZedPro) | Plan::V2(PlanV2::ZedPro)))
2113 && user_store
2114 .subscription_period()
2115 .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
2116 .is_some_and(|date| date < chrono::Utc::now())
2117 {
2118 OnboardingUpsell::set_dismissed(true, cx);
2119 return false;
2120 }
2121
2122 match &self.active_view {
2123 ActiveView::History | ActiveView::Configuration => false,
2124 ActiveView::ExternalAgentThread { thread_view, .. }
2125 if thread_view.read(cx).as_native_thread(cx).is_none() =>
2126 {
2127 false
2128 }
2129 _ => {
2130 let history_is_empty = self.acp_history_store.read(cx).is_empty(cx)
2131 && self
2132 .history_store
2133 .update(cx, |store, cx| store.recent_entries(1, cx).is_empty());
2134
2135 let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
2136 .providers()
2137 .iter()
2138 .any(|provider| {
2139 provider.is_authenticated(cx)
2140 && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2141 });
2142
2143 history_is_empty || !has_configured_non_zed_providers
2144 }
2145 }
2146 }
2147
2148 fn render_onboarding(
2149 &self,
2150 _window: &mut Window,
2151 cx: &mut Context<Self>,
2152 ) -> Option<impl IntoElement> {
2153 if !self.should_render_onboarding(cx) {
2154 return None;
2155 }
2156
2157 let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
2158
2159 Some(
2160 div()
2161 .when(text_thread_view, |this| {
2162 this.bg(cx.theme().colors().editor_background)
2163 })
2164 .child(self.onboarding.clone()),
2165 )
2166 }
2167
2168 fn render_trial_end_upsell(
2169 &self,
2170 _window: &mut Window,
2171 cx: &mut Context<Self>,
2172 ) -> Option<impl IntoElement> {
2173 if !self.should_render_trial_end_upsell(cx) {
2174 return None;
2175 }
2176
2177 let plan = self.user_store.read(cx).plan()?;
2178
2179 Some(
2180 v_flex()
2181 .absolute()
2182 .inset_0()
2183 .size_full()
2184 .bg(cx.theme().colors().panel_background)
2185 .opacity(0.85)
2186 .block_mouse_except_scroll()
2187 .child(EndTrialUpsell::new(
2188 plan,
2189 Arc::new({
2190 let this = cx.entity();
2191 move |_, cx| {
2192 this.update(cx, |_this, cx| {
2193 TrialEndUpsell::set_dismissed(true, cx);
2194 cx.notify();
2195 });
2196 }
2197 }),
2198 )),
2199 )
2200 }
2201
2202 fn render_configuration_error(
2203 &self,
2204 border_bottom: bool,
2205 configuration_error: &ConfigurationError,
2206 focus_handle: &FocusHandle,
2207 window: &mut Window,
2208 cx: &mut App,
2209 ) -> impl IntoElement {
2210 let zed_provider_configured = AgentSettings::get_global(cx)
2211 .default_model
2212 .as_ref()
2213 .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
2214
2215 let callout = if zed_provider_configured {
2216 Callout::new()
2217 .icon(IconName::Warning)
2218 .severity(Severity::Warning)
2219 .when(border_bottom, |this| {
2220 this.border_position(ui::BorderPosition::Bottom)
2221 })
2222 .title("Sign in to continue using Zed as your LLM provider.")
2223 .actions_slot(
2224 Button::new("sign_in", "Sign In")
2225 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2226 .label_size(LabelSize::Small)
2227 .on_click({
2228 let workspace = self.workspace.clone();
2229 move |_, _, cx| {
2230 let Ok(client) =
2231 workspace.update(cx, |workspace, _| workspace.client().clone())
2232 else {
2233 return;
2234 };
2235
2236 cx.spawn(async move |cx| {
2237 client.sign_in_with_optional_connect(true, cx).await
2238 })
2239 .detach_and_log_err(cx);
2240 }
2241 }),
2242 )
2243 } else {
2244 Callout::new()
2245 .icon(IconName::Warning)
2246 .severity(Severity::Warning)
2247 .when(border_bottom, |this| {
2248 this.border_position(ui::BorderPosition::Bottom)
2249 })
2250 .title(configuration_error.to_string())
2251 .actions_slot(
2252 Button::new("settings", "Configure")
2253 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2254 .label_size(LabelSize::Small)
2255 .key_binding(
2256 KeyBinding::for_action_in(&OpenSettings, focus_handle, window, cx)
2257 .map(|kb| kb.size(rems_from_px(12.))),
2258 )
2259 .on_click(|_event, window, cx| {
2260 window.dispatch_action(OpenSettings.boxed_clone(), cx)
2261 }),
2262 )
2263 };
2264
2265 match configuration_error {
2266 ConfigurationError::ModelNotFound
2267 | ConfigurationError::ProviderNotAuthenticated(_)
2268 | ConfigurationError::NoProvider => callout.into_any_element(),
2269 }
2270 }
2271
2272 fn render_prompt_editor(
2273 &self,
2274 context_editor: &Entity<TextThreadEditor>,
2275 buffer_search_bar: &Entity<BufferSearchBar>,
2276 window: &mut Window,
2277 cx: &mut Context<Self>,
2278 ) -> Div {
2279 let mut registrar = buffer_search::DivRegistrar::new(
2280 |this, _, _cx| match &this.active_view {
2281 ActiveView::TextThread {
2282 buffer_search_bar, ..
2283 } => Some(buffer_search_bar.clone()),
2284 _ => None,
2285 },
2286 cx,
2287 );
2288 BufferSearchBar::register(&mut registrar);
2289 registrar
2290 .into_div()
2291 .size_full()
2292 .relative()
2293 .map(|parent| {
2294 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
2295 if buffer_search_bar.is_dismissed() {
2296 return parent;
2297 }
2298 parent.child(
2299 div()
2300 .p(DynamicSpacing::Base08.rems(cx))
2301 .border_b_1()
2302 .border_color(cx.theme().colors().border_variant)
2303 .bg(cx.theme().colors().editor_background)
2304 .child(buffer_search_bar.render(window, cx)),
2305 )
2306 })
2307 })
2308 .child(context_editor.clone())
2309 .child(self.render_drag_target(cx))
2310 }
2311
2312 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
2313 let is_local = self.project.read(cx).is_local();
2314 div()
2315 .invisible()
2316 .absolute()
2317 .top_0()
2318 .right_0()
2319 .bottom_0()
2320 .left_0()
2321 .bg(cx.theme().colors().drop_target_background)
2322 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
2323 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
2324 .when(is_local, |this| {
2325 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
2326 })
2327 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
2328 let item = tab.pane.read(cx).item_for_index(tab.ix);
2329 let project_paths = item
2330 .and_then(|item| item.project_path(cx))
2331 .into_iter()
2332 .collect::<Vec<_>>();
2333 this.handle_drop(project_paths, vec![], window, cx);
2334 }))
2335 .on_drop(
2336 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2337 let project_paths = selection
2338 .items()
2339 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
2340 .collect::<Vec<_>>();
2341 this.handle_drop(project_paths, vec![], window, cx);
2342 }),
2343 )
2344 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
2345 let tasks = paths
2346 .paths()
2347 .iter()
2348 .map(|path| {
2349 Workspace::project_path_for_path(this.project.clone(), path, false, cx)
2350 })
2351 .collect::<Vec<_>>();
2352 cx.spawn_in(window, async move |this, cx| {
2353 let mut paths = vec![];
2354 let mut added_worktrees = vec![];
2355 let opened_paths = futures::future::join_all(tasks).await;
2356 for entry in opened_paths {
2357 if let Some((worktree, project_path)) = entry.log_err() {
2358 added_worktrees.push(worktree);
2359 paths.push(project_path);
2360 }
2361 }
2362 this.update_in(cx, |this, window, cx| {
2363 this.handle_drop(paths, added_worktrees, window, cx);
2364 })
2365 .ok();
2366 })
2367 .detach();
2368 }))
2369 }
2370
2371 fn handle_drop(
2372 &mut self,
2373 paths: Vec<ProjectPath>,
2374 added_worktrees: Vec<Entity<Worktree>>,
2375 window: &mut Window,
2376 cx: &mut Context<Self>,
2377 ) {
2378 match &self.active_view {
2379 ActiveView::ExternalAgentThread { thread_view } => {
2380 thread_view.update(cx, |thread_view, cx| {
2381 thread_view.insert_dragged_files(paths, added_worktrees, window, cx);
2382 });
2383 }
2384 ActiveView::TextThread { context_editor, .. } => {
2385 context_editor.update(cx, |context_editor, cx| {
2386 TextThreadEditor::insert_dragged_files(
2387 context_editor,
2388 paths,
2389 added_worktrees,
2390 window,
2391 cx,
2392 );
2393 });
2394 }
2395 ActiveView::History | ActiveView::Configuration => {}
2396 }
2397 }
2398
2399 fn key_context(&self) -> KeyContext {
2400 let mut key_context = KeyContext::new_with_defaults();
2401 key_context.add("AgentPanel");
2402 match &self.active_view {
2403 ActiveView::ExternalAgentThread { .. } => key_context.add("external_agent_thread"),
2404 ActiveView::TextThread { .. } => key_context.add("prompt_editor"),
2405 ActiveView::History | ActiveView::Configuration => {}
2406 }
2407 key_context
2408 }
2409}
2410
2411impl Render for AgentPanel {
2412 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2413 // WARNING: Changes to this element hierarchy can have
2414 // non-obvious implications to the layout of children.
2415 //
2416 // If you need to change it, please confirm:
2417 // - The message editor expands (cmd-option-esc) correctly
2418 // - When expanded, the buttons at the bottom of the panel are displayed correctly
2419 // - Font size works as expected and can be changed with cmd-+/cmd-
2420 // - Scrolling in all views works as expected
2421 // - Files can be dropped into the panel
2422 let content = v_flex()
2423 .relative()
2424 .size_full()
2425 .justify_between()
2426 .key_context(self.key_context())
2427 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
2428 this.new_thread(action, window, cx);
2429 }))
2430 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
2431 this.open_history(window, cx);
2432 }))
2433 .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
2434 this.open_configuration(window, cx);
2435 }))
2436 .on_action(cx.listener(Self::open_active_thread_as_markdown))
2437 .on_action(cx.listener(Self::deploy_rules_library))
2438 .on_action(cx.listener(Self::go_back))
2439 .on_action(cx.listener(Self::toggle_navigation_menu))
2440 .on_action(cx.listener(Self::toggle_options_menu))
2441 .on_action(cx.listener(Self::increase_font_size))
2442 .on_action(cx.listener(Self::decrease_font_size))
2443 .on_action(cx.listener(Self::reset_font_size))
2444 .on_action(cx.listener(Self::toggle_zoom))
2445 .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
2446 if let Some(thread_view) = this.active_thread_view() {
2447 thread_view.update(cx, |thread_view, cx| thread_view.reauthenticate(window, cx))
2448 }
2449 }))
2450 .child(self.render_toolbar(window, cx))
2451 .children(self.render_onboarding(window, cx))
2452 .map(|parent| match &self.active_view {
2453 ActiveView::ExternalAgentThread { thread_view, .. } => parent
2454 .child(thread_view.clone())
2455 .child(self.render_drag_target(cx)),
2456 ActiveView::History => parent.child(self.acp_history.clone()),
2457 ActiveView::TextThread {
2458 context_editor,
2459 buffer_search_bar,
2460 ..
2461 } => {
2462 let model_registry = LanguageModelRegistry::read_global(cx);
2463 let configuration_error =
2464 model_registry.configuration_error(model_registry.default_model(), cx);
2465 parent
2466 .map(|this| {
2467 if !self.should_render_onboarding(cx)
2468 && let Some(err) = configuration_error.as_ref()
2469 {
2470 this.child(self.render_configuration_error(
2471 true,
2472 err,
2473 &self.focus_handle(cx),
2474 window,
2475 cx,
2476 ))
2477 } else {
2478 this
2479 }
2480 })
2481 .child(self.render_prompt_editor(
2482 context_editor,
2483 buffer_search_bar,
2484 window,
2485 cx,
2486 ))
2487 }
2488 ActiveView::Configuration => parent.children(self.configuration.clone()),
2489 })
2490 .children(self.render_trial_end_upsell(window, cx));
2491
2492 match self.active_view.which_font_size_used() {
2493 WhichFontSize::AgentFont => {
2494 WithRemSize::new(ThemeSettings::get_global(cx).agent_font_size(cx))
2495 .size_full()
2496 .child(content)
2497 .into_any()
2498 }
2499 _ => content.into_any(),
2500 }
2501 }
2502}
2503
2504struct PromptLibraryInlineAssist {
2505 workspace: WeakEntity<Workspace>,
2506}
2507
2508impl PromptLibraryInlineAssist {
2509 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
2510 Self { workspace }
2511 }
2512}
2513
2514impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
2515 fn assist(
2516 &self,
2517 prompt_editor: &Entity<Editor>,
2518 initial_prompt: Option<String>,
2519 window: &mut Window,
2520 cx: &mut Context<RulesLibrary>,
2521 ) {
2522 InlineAssistant::update_global(cx, |assistant, cx| {
2523 let Some(project) = self
2524 .workspace
2525 .upgrade()
2526 .map(|workspace| workspace.read(cx).project().downgrade())
2527 else {
2528 return;
2529 };
2530 let prompt_store = None;
2531 let thread_store = None;
2532 let text_thread_store = None;
2533 let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
2534 assistant.assist(
2535 prompt_editor,
2536 self.workspace.clone(),
2537 context_store,
2538 project,
2539 prompt_store,
2540 thread_store,
2541 text_thread_store,
2542 initial_prompt,
2543 window,
2544 cx,
2545 )
2546 })
2547 }
2548
2549 fn focus_agent_panel(
2550 &self,
2551 workspace: &mut Workspace,
2552 window: &mut Window,
2553 cx: &mut Context<Workspace>,
2554 ) -> bool {
2555 workspace.focus_panel::<AgentPanel>(window, cx).is_some()
2556 }
2557}
2558
2559pub struct ConcreteAssistantPanelDelegate;
2560
2561impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
2562 fn active_context_editor(
2563 &self,
2564 workspace: &mut Workspace,
2565 _window: &mut Window,
2566 cx: &mut Context<Workspace>,
2567 ) -> Option<Entity<TextThreadEditor>> {
2568 let panel = workspace.panel::<AgentPanel>(cx)?;
2569 panel.read(cx).active_context_editor()
2570 }
2571
2572 fn open_saved_context(
2573 &self,
2574 workspace: &mut Workspace,
2575 path: Arc<Path>,
2576 window: &mut Window,
2577 cx: &mut Context<Workspace>,
2578 ) -> Task<Result<()>> {
2579 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
2580 return Task::ready(Err(anyhow!("Agent panel not found")));
2581 };
2582
2583 panel.update(cx, |panel, cx| {
2584 panel.open_saved_prompt_editor(path, window, cx)
2585 })
2586 }
2587
2588 fn open_remote_context(
2589 &self,
2590 _workspace: &mut Workspace,
2591 _context_id: assistant_context::ContextId,
2592 _window: &mut Window,
2593 _cx: &mut Context<Workspace>,
2594 ) -> Task<Result<Entity<TextThreadEditor>>> {
2595 Task::ready(Err(anyhow!("opening remote context not implemented")))
2596 }
2597
2598 fn quote_selection(
2599 &self,
2600 workspace: &mut Workspace,
2601 selection_ranges: Vec<Range<Anchor>>,
2602 buffer: Entity<MultiBuffer>,
2603 window: &mut Window,
2604 cx: &mut Context<Workspace>,
2605 ) {
2606 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
2607 return;
2608 };
2609
2610 if !panel.focus_handle(cx).contains_focused(window, cx) {
2611 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
2612 }
2613
2614 panel.update(cx, |_, cx| {
2615 // Wait to create a new context until the workspace is no longer
2616 // being updated.
2617 cx.defer_in(window, move |panel, window, cx| {
2618 if let Some(thread_view) = panel.active_thread_view() {
2619 thread_view.update(cx, |thread_view, cx| {
2620 thread_view.insert_selections(window, cx);
2621 });
2622 } else if let Some(context_editor) = panel.active_context_editor() {
2623 let snapshot = buffer.read(cx).snapshot(cx);
2624 let selection_ranges = selection_ranges
2625 .into_iter()
2626 .map(|range| range.to_point(&snapshot))
2627 .collect::<Vec<_>>();
2628
2629 context_editor.update(cx, |context_editor, cx| {
2630 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
2631 });
2632 }
2633 });
2634 });
2635 }
2636}
2637
2638struct OnboardingUpsell;
2639
2640impl Dismissable for OnboardingUpsell {
2641 const KEY: &'static str = "dismissed-trial-upsell";
2642}
2643
2644struct TrialEndUpsell;
2645
2646impl Dismissable for TrialEndUpsell {
2647 const KEY: &'static str = "dismissed-trial-end-upsell";
2648}