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