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 if let Some(title_editor) = thread_view.read(cx).title_editor() {
2079 div()
2080 .w_full()
2081 .on_action({
2082 let thread_view = thread_view.downgrade();
2083 move |_: &menu::Confirm, window, cx| {
2084 if let Some(thread_view) = thread_view.upgrade() {
2085 thread_view.focus_handle(cx).focus(window);
2086 }
2087 }
2088 })
2089 .on_action({
2090 let thread_view = thread_view.downgrade();
2091 move |_: &editor::actions::Cancel, window, cx| {
2092 if let Some(thread_view) = thread_view.upgrade() {
2093 thread_view.focus_handle(cx).focus(window);
2094 }
2095 }
2096 })
2097 .child(title_editor)
2098 .into_any_element()
2099 } else {
2100 Label::new(thread_view.read(cx).title(cx))
2101 .truncate()
2102 .into_any_element()
2103 }
2104 }
2105 ActiveView::TextThread {
2106 title_editor,
2107 context_editor,
2108 ..
2109 } => {
2110 let summary = context_editor.read(cx).context().read(cx).summary();
2111
2112 match summary {
2113 ContextSummary::Pending => Label::new(ContextSummary::DEFAULT)
2114 .truncate()
2115 .into_any_element(),
2116 ContextSummary::Content(summary) => {
2117 if summary.done {
2118 div()
2119 .w_full()
2120 .child(title_editor.clone())
2121 .into_any_element()
2122 } else {
2123 Label::new(LOADING_SUMMARY_PLACEHOLDER)
2124 .truncate()
2125 .into_any_element()
2126 }
2127 }
2128 ContextSummary::Error => h_flex()
2129 .w_full()
2130 .child(title_editor.clone())
2131 .child(
2132 IconButton::new("retry-summary-generation", IconName::RotateCcw)
2133 .icon_size(IconSize::Small)
2134 .on_click({
2135 let context_editor = context_editor.clone();
2136 move |_, _window, cx| {
2137 context_editor.update(cx, |context_editor, cx| {
2138 context_editor.regenerate_summary(cx);
2139 });
2140 }
2141 })
2142 .tooltip(move |_window, cx| {
2143 cx.new(|_| {
2144 Tooltip::new("Failed to generate title")
2145 .meta("Click to try again")
2146 })
2147 .into()
2148 }),
2149 )
2150 .into_any_element(),
2151 }
2152 }
2153 ActiveView::History => Label::new("History").truncate().into_any_element(),
2154 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
2155 };
2156
2157 h_flex()
2158 .key_context("TitleEditor")
2159 .id("TitleEditor")
2160 .flex_grow()
2161 .w_full()
2162 .max_w_full()
2163 .overflow_x_scroll()
2164 .child(content)
2165 .into_any()
2166 }
2167
2168 fn render_panel_options_menu(
2169 &self,
2170 window: &mut Window,
2171 cx: &mut Context<Self>,
2172 ) -> impl IntoElement {
2173 let user_store = self.user_store.read(cx);
2174 let usage = user_store.model_request_usage();
2175 let account_url = zed_urls::account_url(cx);
2176
2177 let focus_handle = self.focus_handle(cx);
2178
2179 let full_screen_label = if self.is_zoomed(window, cx) {
2180 "Disable Full Screen"
2181 } else {
2182 "Enable Full Screen"
2183 };
2184
2185 PopoverMenu::new("agent-options-menu")
2186 .trigger_with_tooltip(
2187 IconButton::new("agent-options-menu", IconName::Ellipsis)
2188 .icon_size(IconSize::Small),
2189 {
2190 let focus_handle = focus_handle.clone();
2191 move |window, cx| {
2192 Tooltip::for_action_in(
2193 "Toggle Agent Menu",
2194 &ToggleOptionsMenu,
2195 &focus_handle,
2196 window,
2197 cx,
2198 )
2199 }
2200 },
2201 )
2202 .anchor(Corner::TopRight)
2203 .with_handle(self.agent_panel_menu_handle.clone())
2204 .menu({
2205 move |window, cx| {
2206 Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
2207 menu = menu.context(focus_handle.clone());
2208 if let Some(usage) = usage {
2209 menu = menu
2210 .header_with_link("Prompt Usage", "Manage", account_url.clone())
2211 .custom_entry(
2212 move |_window, cx| {
2213 let used_percentage = match usage.limit {
2214 UsageLimit::Limited(limit) => {
2215 Some((usage.amount as f32 / limit as f32) * 100.)
2216 }
2217 UsageLimit::Unlimited => None,
2218 };
2219
2220 h_flex()
2221 .flex_1()
2222 .gap_1p5()
2223 .children(used_percentage.map(|percent| {
2224 ProgressBar::new("usage", percent, 100., cx)
2225 }))
2226 .child(
2227 Label::new(match usage.limit {
2228 UsageLimit::Limited(limit) => {
2229 format!("{} / {limit}", usage.amount)
2230 }
2231 UsageLimit::Unlimited => {
2232 format!("{} / ∞", usage.amount)
2233 }
2234 })
2235 .size(LabelSize::Small)
2236 .color(Color::Muted),
2237 )
2238 .into_any_element()
2239 },
2240 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
2241 )
2242 .separator()
2243 }
2244
2245 menu = menu
2246 .header("MCP Servers")
2247 .action(
2248 "View Server Extensions",
2249 Box::new(zed_actions::Extensions {
2250 category_filter: Some(
2251 zed_actions::ExtensionCategoryFilter::ContextServers,
2252 ),
2253 id: None,
2254 }),
2255 )
2256 .action("Add Custom Server…", Box::new(AddContextServer))
2257 .separator();
2258
2259 menu = menu
2260 .action("Rules…", Box::new(OpenRulesLibrary::default()))
2261 .action("Settings", Box::new(OpenSettings))
2262 .separator()
2263 .action(full_screen_label, Box::new(ToggleZoom));
2264 menu
2265 }))
2266 }
2267 })
2268 }
2269
2270 fn render_recent_entries_menu(
2271 &self,
2272 icon: IconName,
2273 corner: Corner,
2274 cx: &mut Context<Self>,
2275 ) -> impl IntoElement {
2276 let focus_handle = self.focus_handle(cx);
2277
2278 PopoverMenu::new("agent-nav-menu")
2279 .trigger_with_tooltip(
2280 IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
2281 {
2282 move |window, cx| {
2283 Tooltip::for_action_in(
2284 "Toggle Recent Threads",
2285 &ToggleNavigationMenu,
2286 &focus_handle,
2287 window,
2288 cx,
2289 )
2290 }
2291 },
2292 )
2293 .anchor(corner)
2294 .with_handle(self.assistant_navigation_menu_handle.clone())
2295 .menu({
2296 let menu = self.assistant_navigation_menu.clone();
2297 move |window, cx| {
2298 if let Some(menu) = menu.as_ref() {
2299 menu.update(cx, |_, cx| {
2300 cx.defer_in(window, |menu, window, cx| {
2301 menu.rebuild(window, cx);
2302 });
2303 })
2304 }
2305 menu.clone()
2306 }
2307 })
2308 }
2309
2310 fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
2311 let focus_handle = self.focus_handle(cx);
2312
2313 IconButton::new("go-back", IconName::ArrowLeft)
2314 .icon_size(IconSize::Small)
2315 .on_click(cx.listener(|this, _, window, cx| {
2316 this.go_back(&workspace::GoBack, window, cx);
2317 }))
2318 .tooltip({
2319 move |window, cx| {
2320 Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, window, cx)
2321 }
2322 })
2323 }
2324
2325 fn render_toolbar_old(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2326 let focus_handle = self.focus_handle(cx);
2327
2328 let active_thread = match &self.active_view {
2329 ActiveView::Thread { thread, .. } => Some(thread.read(cx).thread().clone()),
2330 ActiveView::ExternalAgentThread { .. }
2331 | ActiveView::TextThread { .. }
2332 | ActiveView::History
2333 | ActiveView::Configuration => None,
2334 };
2335
2336 let new_thread_menu = PopoverMenu::new("new_thread_menu")
2337 .trigger_with_tooltip(
2338 IconButton::new("new_thread_menu_btn", IconName::Plus).icon_size(IconSize::Small),
2339 Tooltip::text("New Thread…"),
2340 )
2341 .anchor(Corner::TopRight)
2342 .with_handle(self.new_thread_menu_handle.clone())
2343 .menu({
2344 move |window, cx| {
2345 let active_thread = active_thread.clone();
2346 Some(ContextMenu::build(window, cx, |mut menu, _window, cx| {
2347 menu = menu
2348 .context(focus_handle.clone())
2349 .when_some(active_thread, |this, active_thread| {
2350 let thread = active_thread.read(cx);
2351
2352 if !thread.is_empty() {
2353 let thread_id = thread.id().clone();
2354 this.item(
2355 ContextMenuEntry::new("New From Summary")
2356 .icon(IconName::ThreadFromSummary)
2357 .icon_color(Color::Muted)
2358 .handler(move |window, cx| {
2359 window.dispatch_action(
2360 Box::new(NewThread {
2361 from_thread_id: Some(thread_id.clone()),
2362 }),
2363 cx,
2364 );
2365 }),
2366 )
2367 } else {
2368 this
2369 }
2370 })
2371 .item(
2372 ContextMenuEntry::new("New Thread")
2373 .icon(IconName::Thread)
2374 .icon_color(Color::Muted)
2375 .action(NewThread::default().boxed_clone())
2376 .handler(move |window, cx| {
2377 window.dispatch_action(
2378 NewThread::default().boxed_clone(),
2379 cx,
2380 );
2381 }),
2382 )
2383 .item(
2384 ContextMenuEntry::new("New Text Thread")
2385 .icon(IconName::TextThread)
2386 .icon_color(Color::Muted)
2387 .action(NewTextThread.boxed_clone())
2388 .handler(move |window, cx| {
2389 window.dispatch_action(NewTextThread.boxed_clone(), cx);
2390 }),
2391 );
2392 menu
2393 }))
2394 }
2395 });
2396
2397 h_flex()
2398 .id("assistant-toolbar")
2399 .h(Tab::container_height(cx))
2400 .max_w_full()
2401 .flex_none()
2402 .justify_between()
2403 .gap_2()
2404 .bg(cx.theme().colors().tab_bar_background)
2405 .border_b_1()
2406 .border_color(cx.theme().colors().border)
2407 .child(
2408 h_flex()
2409 .size_full()
2410 .pl_1()
2411 .gap_1()
2412 .child(match &self.active_view {
2413 ActiveView::History | ActiveView::Configuration => div()
2414 .pl(DynamicSpacing::Base04.rems(cx))
2415 .child(self.render_toolbar_back_button(cx))
2416 .into_any_element(),
2417 _ => self
2418 .render_recent_entries_menu(IconName::MenuAlt, Corner::TopLeft, cx)
2419 .into_any_element(),
2420 })
2421 .child(self.render_title_view(window, cx)),
2422 )
2423 .child(
2424 h_flex()
2425 .h_full()
2426 .gap_2()
2427 .children(self.render_token_count(cx))
2428 .child(
2429 h_flex()
2430 .h_full()
2431 .gap(DynamicSpacing::Base02.rems(cx))
2432 .px(DynamicSpacing::Base08.rems(cx))
2433 .border_l_1()
2434 .border_color(cx.theme().colors().border)
2435 .child(new_thread_menu)
2436 .child(self.render_panel_options_menu(window, cx)),
2437 ),
2438 )
2439 }
2440
2441 fn render_toolbar_new(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2442 let focus_handle = self.focus_handle(cx);
2443
2444 let active_thread = match &self.active_view {
2445 ActiveView::ExternalAgentThread { thread_view } => {
2446 thread_view.read(cx).as_native_thread(cx)
2447 }
2448 ActiveView::Thread { .. }
2449 | ActiveView::TextThread { .. }
2450 | ActiveView::History
2451 | ActiveView::Configuration => None,
2452 };
2453
2454 let new_thread_menu = PopoverMenu::new("new_thread_menu")
2455 .trigger_with_tooltip(
2456 IconButton::new("new_thread_menu_btn", IconName::Plus).icon_size(IconSize::Small),
2457 {
2458 let focus_handle = focus_handle.clone();
2459 move |window, cx| {
2460 Tooltip::for_action_in(
2461 "New…",
2462 &ToggleNewThreadMenu,
2463 &focus_handle,
2464 window,
2465 cx,
2466 )
2467 }
2468 },
2469 )
2470 .anchor(Corner::TopLeft)
2471 .with_handle(self.new_thread_menu_handle.clone())
2472 .menu({
2473 let workspace = self.workspace.clone();
2474
2475 move |window, cx| {
2476 let active_thread = active_thread.clone();
2477 Some(ContextMenu::build(window, cx, |mut menu, _window, cx| {
2478 menu = menu
2479 .context(focus_handle.clone())
2480 .header("Zed Agent")
2481 .when_some(active_thread, |this, active_thread| {
2482 let thread = active_thread.read(cx);
2483
2484 if !thread.is_empty() {
2485 let session_id = thread.id().clone();
2486 this.item(
2487 ContextMenuEntry::new("New From Summary")
2488 .icon(IconName::ThreadFromSummary)
2489 .icon_color(Color::Muted)
2490 .handler(move |window, cx| {
2491 window.dispatch_action(
2492 Box::new(NewNativeAgentThreadFromSummary {
2493 from_session_id: session_id.clone(),
2494 }),
2495 cx,
2496 );
2497 }),
2498 )
2499 } else {
2500 this
2501 }
2502 })
2503 .item(
2504 ContextMenuEntry::new("New Thread")
2505 .action(NewThread::default().boxed_clone())
2506 .icon(IconName::Thread)
2507 .icon_color(Color::Muted)
2508 .handler({
2509 let workspace = workspace.clone();
2510 move |window, cx| {
2511 if let Some(workspace) = workspace.upgrade() {
2512 workspace.update(cx, |workspace, cx| {
2513 if let Some(panel) =
2514 workspace.panel::<AgentPanel>(cx)
2515 {
2516 panel.update(cx, |panel, cx| {
2517 panel.set_selected_agent(
2518 AgentType::NativeAgent,
2519 window,
2520 cx,
2521 );
2522 });
2523 }
2524 });
2525 }
2526 }
2527 }),
2528 )
2529 .item(
2530 ContextMenuEntry::new("New Text Thread")
2531 .icon(IconName::TextThread)
2532 .icon_color(Color::Muted)
2533 .action(NewTextThread.boxed_clone())
2534 .handler({
2535 let workspace = workspace.clone();
2536 move |window, cx| {
2537 if let Some(workspace) = workspace.upgrade() {
2538 workspace.update(cx, |workspace, cx| {
2539 if let Some(panel) =
2540 workspace.panel::<AgentPanel>(cx)
2541 {
2542 panel.update(cx, |panel, cx| {
2543 panel.set_selected_agent(
2544 AgentType::TextThread,
2545 window,
2546 cx,
2547 );
2548 });
2549 }
2550 });
2551 }
2552 }
2553 }),
2554 )
2555 .separator()
2556 .header("External Agents")
2557 .when(cx.has_flag::<GeminiAndNativeFeatureFlag>(), |menu| {
2558 menu.item(
2559 ContextMenuEntry::new("New Gemini CLI Thread")
2560 .icon(IconName::AiGemini)
2561 .icon_color(Color::Muted)
2562 .handler({
2563 let workspace = workspace.clone();
2564 move |window, cx| {
2565 if let Some(workspace) = workspace.upgrade() {
2566 workspace.update(cx, |workspace, cx| {
2567 if let Some(panel) =
2568 workspace.panel::<AgentPanel>(cx)
2569 {
2570 panel.update(cx, |panel, cx| {
2571 panel.set_selected_agent(
2572 AgentType::Gemini,
2573 window,
2574 cx,
2575 );
2576 });
2577 }
2578 });
2579 }
2580 }
2581 }),
2582 )
2583 })
2584 .when(cx.has_flag::<ClaudeCodeFeatureFlag>(), |menu| {
2585 menu.item(
2586 ContextMenuEntry::new("New Claude Code Thread")
2587 .icon(IconName::AiClaude)
2588 .icon_color(Color::Muted)
2589 .handler({
2590 let workspace = workspace.clone();
2591 move |window, cx| {
2592 if let Some(workspace) = workspace.upgrade() {
2593 workspace.update(cx, |workspace, cx| {
2594 if let Some(panel) =
2595 workspace.panel::<AgentPanel>(cx)
2596 {
2597 panel.update(cx, |panel, cx| {
2598 panel.set_selected_agent(
2599 AgentType::ClaudeCode,
2600 window,
2601 cx,
2602 );
2603 });
2604 }
2605 });
2606 }
2607 }
2608 }),
2609 )
2610 });
2611 menu
2612 }))
2613 }
2614 });
2615
2616 let selected_agent_label = self.selected_agent.label().into();
2617 let selected_agent = div()
2618 .id("selected_agent_icon")
2619 .when_some(self.selected_agent.icon(), |this, icon| {
2620 this.px(DynamicSpacing::Base02.rems(cx))
2621 .child(Icon::new(icon).color(Color::Muted))
2622 .tooltip(move |window, cx| {
2623 Tooltip::with_meta(
2624 selected_agent_label.clone(),
2625 None,
2626 "Selected Agent",
2627 window,
2628 cx,
2629 )
2630 })
2631 })
2632 .into_any_element();
2633
2634 h_flex()
2635 .id("agent-panel-toolbar")
2636 .h(Tab::container_height(cx))
2637 .max_w_full()
2638 .flex_none()
2639 .justify_between()
2640 .gap_2()
2641 .bg(cx.theme().colors().tab_bar_background)
2642 .border_b_1()
2643 .border_color(cx.theme().colors().border)
2644 .child(
2645 h_flex()
2646 .size_full()
2647 .gap(DynamicSpacing::Base04.rems(cx))
2648 .pl(DynamicSpacing::Base04.rems(cx))
2649 .child(match &self.active_view {
2650 ActiveView::History | ActiveView::Configuration => {
2651 self.render_toolbar_back_button(cx).into_any_element()
2652 }
2653 _ => selected_agent.into_any_element(),
2654 })
2655 .child(self.render_title_view(window, cx)),
2656 )
2657 .child(
2658 h_flex()
2659 .flex_none()
2660 .gap(DynamicSpacing::Base02.rems(cx))
2661 .pl(DynamicSpacing::Base04.rems(cx))
2662 .pr(DynamicSpacing::Base06.rems(cx))
2663 .child(new_thread_menu)
2664 .child(self.render_recent_entries_menu(
2665 IconName::MenuAltTemp,
2666 Corner::TopRight,
2667 cx,
2668 ))
2669 .child(self.render_panel_options_menu(window, cx)),
2670 )
2671 }
2672
2673 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2674 if cx.has_flag::<feature_flags::GeminiAndNativeFeatureFlag>()
2675 || cx.has_flag::<feature_flags::ClaudeCodeFeatureFlag>()
2676 {
2677 self.render_toolbar_new(window, cx).into_any_element()
2678 } else {
2679 self.render_toolbar_old(window, cx).into_any_element()
2680 }
2681 }
2682
2683 fn render_token_count(&self, cx: &App) -> Option<AnyElement> {
2684 match &self.active_view {
2685 ActiveView::Thread {
2686 thread,
2687 message_editor,
2688 ..
2689 } => {
2690 let active_thread = thread.read(cx);
2691 let message_editor = message_editor.read(cx);
2692
2693 let editor_empty = message_editor.is_editor_fully_empty(cx);
2694
2695 if active_thread.is_empty() && editor_empty {
2696 return None;
2697 }
2698
2699 let thread = active_thread.thread().read(cx);
2700 let is_generating = thread.is_generating();
2701 let conversation_token_usage = thread.total_token_usage()?;
2702
2703 let (total_token_usage, is_estimating) =
2704 if let Some((editing_message_id, unsent_tokens)) =
2705 active_thread.editing_message_id()
2706 {
2707 let combined = thread
2708 .token_usage_up_to_message(editing_message_id)
2709 .add(unsent_tokens);
2710
2711 (combined, unsent_tokens > 0)
2712 } else {
2713 let unsent_tokens =
2714 message_editor.last_estimated_token_count().unwrap_or(0);
2715 let combined = conversation_token_usage.add(unsent_tokens);
2716
2717 (combined, unsent_tokens > 0)
2718 };
2719
2720 let is_waiting_to_update_token_count =
2721 message_editor.is_waiting_to_update_token_count();
2722
2723 if total_token_usage.total == 0 {
2724 return None;
2725 }
2726
2727 let token_color = match total_token_usage.ratio() {
2728 TokenUsageRatio::Normal if is_estimating => Color::Default,
2729 TokenUsageRatio::Normal => Color::Muted,
2730 TokenUsageRatio::Warning => Color::Warning,
2731 TokenUsageRatio::Exceeded => Color::Error,
2732 };
2733
2734 let token_count = h_flex()
2735 .id("token-count")
2736 .flex_shrink_0()
2737 .gap_0p5()
2738 .when(!is_generating && is_estimating, |parent| {
2739 parent
2740 .child(
2741 h_flex()
2742 .mr_1()
2743 .size_2p5()
2744 .justify_center()
2745 .rounded_full()
2746 .bg(cx.theme().colors().text.opacity(0.1))
2747 .child(
2748 div().size_1().rounded_full().bg(cx.theme().colors().text),
2749 ),
2750 )
2751 .tooltip(move |window, cx| {
2752 Tooltip::with_meta(
2753 "Estimated New Token Count",
2754 None,
2755 format!(
2756 "Current Conversation Tokens: {}",
2757 humanize_token_count(conversation_token_usage.total)
2758 ),
2759 window,
2760 cx,
2761 )
2762 })
2763 })
2764 .child(
2765 Label::new(humanize_token_count(total_token_usage.total))
2766 .size(LabelSize::Small)
2767 .color(token_color)
2768 .map(|label| {
2769 if is_generating || is_waiting_to_update_token_count {
2770 label
2771 .with_animation(
2772 "used-tokens-label",
2773 Animation::new(Duration::from_secs(2))
2774 .repeat()
2775 .with_easing(pulsating_between(0.6, 1.)),
2776 |label, delta| label.alpha(delta),
2777 )
2778 .into_any()
2779 } else {
2780 label.into_any_element()
2781 }
2782 }),
2783 )
2784 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2785 .child(
2786 Label::new(humanize_token_count(total_token_usage.max))
2787 .size(LabelSize::Small)
2788 .color(Color::Muted),
2789 )
2790 .into_any();
2791
2792 Some(token_count)
2793 }
2794 ActiveView::TextThread { context_editor, .. } => {
2795 let element = render_remaining_tokens(context_editor, cx)?;
2796
2797 Some(element.into_any_element())
2798 }
2799 ActiveView::ExternalAgentThread { .. }
2800 | ActiveView::History
2801 | ActiveView::Configuration => None,
2802 }
2803 }
2804
2805 fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
2806 if TrialEndUpsell::dismissed() {
2807 return false;
2808 }
2809
2810 match &self.active_view {
2811 ActiveView::Thread { thread, .. } => {
2812 if thread
2813 .read(cx)
2814 .thread()
2815 .read(cx)
2816 .configured_model()
2817 .is_some_and(|model| {
2818 model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2819 })
2820 {
2821 return false;
2822 }
2823 }
2824 ActiveView::TextThread { .. } => {
2825 if LanguageModelRegistry::global(cx)
2826 .read(cx)
2827 .default_model()
2828 .is_some_and(|model| {
2829 model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2830 })
2831 {
2832 return false;
2833 }
2834 }
2835 ActiveView::ExternalAgentThread { .. }
2836 | ActiveView::History
2837 | ActiveView::Configuration => return false,
2838 }
2839
2840 let plan = self.user_store.read(cx).plan();
2841 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2842
2843 matches!(plan, Some(Plan::ZedFree)) && has_previous_trial
2844 }
2845
2846 fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
2847 if OnboardingUpsell::dismissed() {
2848 return false;
2849 }
2850
2851 match &self.active_view {
2852 ActiveView::History | ActiveView::Configuration => false,
2853 ActiveView::ExternalAgentThread { thread_view, .. }
2854 if thread_view.read(cx).as_native_thread(cx).is_none() =>
2855 {
2856 false
2857 }
2858 _ => {
2859 let history_is_empty = if cx.has_flag::<GeminiAndNativeFeatureFlag>() {
2860 self.acp_history_store.read(cx).is_empty(cx)
2861 } else {
2862 self.history_store
2863 .update(cx, |store, cx| store.recent_entries(1, cx).is_empty())
2864 };
2865
2866 let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
2867 .providers()
2868 .iter()
2869 .any(|provider| {
2870 provider.is_authenticated(cx)
2871 && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2872 });
2873
2874 history_is_empty || !has_configured_non_zed_providers
2875 }
2876 }
2877 }
2878
2879 fn render_onboarding(
2880 &self,
2881 _window: &mut Window,
2882 cx: &mut Context<Self>,
2883 ) -> Option<impl IntoElement> {
2884 if !self.should_render_onboarding(cx) {
2885 return None;
2886 }
2887
2888 let thread_view = matches!(&self.active_view, ActiveView::Thread { .. });
2889 let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
2890
2891 Some(
2892 div()
2893 .when(thread_view, |this| {
2894 this.size_full().bg(cx.theme().colors().panel_background)
2895 })
2896 .when(text_thread_view, |this| {
2897 this.bg(cx.theme().colors().editor_background)
2898 })
2899 .child(self.onboarding.clone()),
2900 )
2901 }
2902
2903 fn render_backdrop(&self, cx: &mut Context<Self>) -> impl IntoElement {
2904 div()
2905 .size_full()
2906 .absolute()
2907 .inset_0()
2908 .bg(cx.theme().colors().panel_background)
2909 .opacity(0.8)
2910 .block_mouse_except_scroll()
2911 }
2912
2913 fn render_trial_end_upsell(
2914 &self,
2915 _window: &mut Window,
2916 cx: &mut Context<Self>,
2917 ) -> Option<impl IntoElement> {
2918 if !self.should_render_trial_end_upsell(cx) {
2919 return None;
2920 }
2921
2922 Some(
2923 v_flex()
2924 .absolute()
2925 .inset_0()
2926 .size_full()
2927 .bg(cx.theme().colors().panel_background)
2928 .opacity(0.85)
2929 .block_mouse_except_scroll()
2930 .child(EndTrialUpsell::new(Arc::new({
2931 let this = cx.entity();
2932 move |_, cx| {
2933 this.update(cx, |_this, cx| {
2934 TrialEndUpsell::set_dismissed(true, cx);
2935 cx.notify();
2936 });
2937 }
2938 }))),
2939 )
2940 }
2941
2942 fn render_empty_state_section_header(
2943 &self,
2944 label: impl Into<SharedString>,
2945 action_slot: Option<AnyElement>,
2946 cx: &mut Context<Self>,
2947 ) -> impl IntoElement {
2948 div().pl_1().pr_1p5().child(
2949 h_flex()
2950 .mt_2()
2951 .pl_1p5()
2952 .pb_1()
2953 .w_full()
2954 .justify_between()
2955 .border_b_1()
2956 .border_color(cx.theme().colors().border_variant)
2957 .child(
2958 Label::new(label.into())
2959 .size(LabelSize::Small)
2960 .color(Color::Muted),
2961 )
2962 .children(action_slot),
2963 )
2964 }
2965
2966 fn render_thread_empty_state(
2967 &self,
2968 window: &mut Window,
2969 cx: &mut Context<Self>,
2970 ) -> impl IntoElement {
2971 let recent_history = self
2972 .history_store
2973 .update(cx, |this, cx| this.recent_entries(6, cx));
2974
2975 let model_registry = LanguageModelRegistry::read_global(cx);
2976
2977 let configuration_error =
2978 model_registry.configuration_error(model_registry.default_model(), cx);
2979
2980 let no_error = configuration_error.is_none();
2981 let focus_handle = self.focus_handle(cx);
2982
2983 v_flex()
2984 .size_full()
2985 .bg(cx.theme().colors().panel_background)
2986 .when(recent_history.is_empty(), |this| {
2987 this.child(
2988 v_flex()
2989 .size_full()
2990 .mx_auto()
2991 .justify_center()
2992 .items_center()
2993 .gap_1()
2994 .child(h_flex().child(Headline::new("Welcome to the Agent Panel")))
2995 .when(no_error, |parent| {
2996 parent
2997 .child(h_flex().child(
2998 Label::new("Ask and build anything.").color(Color::Muted),
2999 ))
3000 .child(
3001 v_flex()
3002 .mt_2()
3003 .gap_1()
3004 .max_w_48()
3005 .child(
3006 Button::new("context", "Add Context")
3007 .label_size(LabelSize::Small)
3008 .icon(IconName::FileCode)
3009 .icon_position(IconPosition::Start)
3010 .icon_size(IconSize::Small)
3011 .icon_color(Color::Muted)
3012 .full_width()
3013 .key_binding(KeyBinding::for_action_in(
3014 &ToggleContextPicker,
3015 &focus_handle,
3016 window,
3017 cx,
3018 ))
3019 .on_click(|_event, window, cx| {
3020 window.dispatch_action(
3021 ToggleContextPicker.boxed_clone(),
3022 cx,
3023 )
3024 }),
3025 )
3026 .child(
3027 Button::new("mode", "Switch Model")
3028 .label_size(LabelSize::Small)
3029 .icon(IconName::DatabaseZap)
3030 .icon_position(IconPosition::Start)
3031 .icon_size(IconSize::Small)
3032 .icon_color(Color::Muted)
3033 .full_width()
3034 .key_binding(KeyBinding::for_action_in(
3035 &ToggleModelSelector,
3036 &focus_handle,
3037 window,
3038 cx,
3039 ))
3040 .on_click(|_event, window, cx| {
3041 window.dispatch_action(
3042 ToggleModelSelector.boxed_clone(),
3043 cx,
3044 )
3045 }),
3046 )
3047 .child(
3048 Button::new("settings", "View Settings")
3049 .label_size(LabelSize::Small)
3050 .icon(IconName::Settings)
3051 .icon_position(IconPosition::Start)
3052 .icon_size(IconSize::Small)
3053 .icon_color(Color::Muted)
3054 .full_width()
3055 .key_binding(KeyBinding::for_action_in(
3056 &OpenSettings,
3057 &focus_handle,
3058 window,
3059 cx,
3060 ))
3061 .on_click(|_event, window, cx| {
3062 window.dispatch_action(
3063 OpenSettings.boxed_clone(),
3064 cx,
3065 )
3066 }),
3067 ),
3068 )
3069 }),
3070 )
3071 })
3072 .when(!recent_history.is_empty(), |parent| {
3073 parent
3074 .overflow_hidden()
3075 .justify_end()
3076 .gap_1()
3077 .child(
3078 self.render_empty_state_section_header(
3079 "Recent",
3080 Some(
3081 Button::new("view-history", "View All")
3082 .style(ButtonStyle::Subtle)
3083 .label_size(LabelSize::Small)
3084 .key_binding(
3085 KeyBinding::for_action_in(
3086 &OpenHistory,
3087 &self.focus_handle(cx),
3088 window,
3089 cx,
3090 )
3091 .map(|kb| kb.size(rems_from_px(12.))),
3092 )
3093 .on_click(move |_event, window, cx| {
3094 window.dispatch_action(OpenHistory.boxed_clone(), cx);
3095 })
3096 .into_any_element(),
3097 ),
3098 cx,
3099 ),
3100 )
3101 .child(
3102 v_flex().p_1().pr_1p5().gap_1().children(
3103 recent_history
3104 .into_iter()
3105 .enumerate()
3106 .map(|(index, entry)| {
3107 // TODO: Add keyboard navigation.
3108 let is_hovered =
3109 self.hovered_recent_history_item == Some(index);
3110 HistoryEntryElement::new(entry, cx.entity().downgrade())
3111 .hovered(is_hovered)
3112 .on_hover(cx.listener(
3113 move |this, is_hovered, _window, cx| {
3114 if *is_hovered {
3115 this.hovered_recent_history_item = Some(index);
3116 } else if this.hovered_recent_history_item
3117 == Some(index)
3118 {
3119 this.hovered_recent_history_item = None;
3120 }
3121 cx.notify();
3122 },
3123 ))
3124 .into_any_element()
3125 }),
3126 ),
3127 )
3128 })
3129 .when_some(configuration_error.as_ref(), |this, err| {
3130 this.child(self.render_configuration_error(false, err, &focus_handle, window, cx))
3131 })
3132 }
3133
3134 fn render_configuration_error(
3135 &self,
3136 border_bottom: bool,
3137 configuration_error: &ConfigurationError,
3138 focus_handle: &FocusHandle,
3139 window: &mut Window,
3140 cx: &mut App,
3141 ) -> impl IntoElement {
3142 let zed_provider_configured = AgentSettings::get_global(cx)
3143 .default_model
3144 .as_ref()
3145 .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
3146
3147 let callout = if zed_provider_configured {
3148 Callout::new()
3149 .icon(IconName::Warning)
3150 .severity(Severity::Warning)
3151 .when(border_bottom, |this| {
3152 this.border_position(ui::BorderPosition::Bottom)
3153 })
3154 .title("Sign in to continue using Zed as your LLM provider.")
3155 .actions_slot(
3156 Button::new("sign_in", "Sign In")
3157 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
3158 .label_size(LabelSize::Small)
3159 .on_click({
3160 let workspace = self.workspace.clone();
3161 move |_, _, cx| {
3162 let Ok(client) =
3163 workspace.update(cx, |workspace, _| workspace.client().clone())
3164 else {
3165 return;
3166 };
3167
3168 cx.spawn(async move |cx| {
3169 client.sign_in_with_optional_connect(true, cx).await
3170 })
3171 .detach_and_log_err(cx);
3172 }
3173 }),
3174 )
3175 } else {
3176 Callout::new()
3177 .icon(IconName::Warning)
3178 .severity(Severity::Warning)
3179 .when(border_bottom, |this| {
3180 this.border_position(ui::BorderPosition::Bottom)
3181 })
3182 .title(configuration_error.to_string())
3183 .actions_slot(
3184 Button::new("settings", "Configure")
3185 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
3186 .label_size(LabelSize::Small)
3187 .key_binding(
3188 KeyBinding::for_action_in(&OpenSettings, focus_handle, window, cx)
3189 .map(|kb| kb.size(rems_from_px(12.))),
3190 )
3191 .on_click(|_event, window, cx| {
3192 window.dispatch_action(OpenSettings.boxed_clone(), cx)
3193 }),
3194 )
3195 };
3196
3197 match configuration_error {
3198 ConfigurationError::ModelNotFound
3199 | ConfigurationError::ProviderNotAuthenticated(_)
3200 | ConfigurationError::NoProvider => callout.into_any_element(),
3201 ConfigurationError::ProviderPendingTermsAcceptance(provider) => {
3202 Banner::new()
3203 .severity(Severity::Warning)
3204 .child(h_flex().w_full().children(
3205 provider.render_accept_terms(
3206 LanguageModelProviderTosView::ThreadEmptyState,
3207 cx,
3208 ),
3209 ))
3210 .into_any_element()
3211 }
3212 }
3213 }
3214
3215 fn render_tool_use_limit_reached(
3216 &self,
3217 window: &mut Window,
3218 cx: &mut Context<Self>,
3219 ) -> Option<AnyElement> {
3220 let active_thread = match &self.active_view {
3221 ActiveView::Thread { thread, .. } => thread,
3222 ActiveView::ExternalAgentThread { .. } => {
3223 return None;
3224 }
3225 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {
3226 return None;
3227 }
3228 };
3229
3230 let thread = active_thread.read(cx).thread().read(cx);
3231
3232 let tool_use_limit_reached = thread.tool_use_limit_reached();
3233 if !tool_use_limit_reached {
3234 return None;
3235 }
3236
3237 let model = thread.configured_model()?.model;
3238
3239 let focus_handle = self.focus_handle(cx);
3240
3241 let banner = Banner::new()
3242 .severity(Severity::Info)
3243 .child(Label::new("Consecutive tool use limit reached.").size(LabelSize::Small))
3244 .action_slot(
3245 h_flex()
3246 .gap_1()
3247 .child(
3248 Button::new("continue-conversation", "Continue")
3249 .layer(ElevationIndex::ModalSurface)
3250 .label_size(LabelSize::Small)
3251 .key_binding(
3252 KeyBinding::for_action_in(
3253 &ContinueThread,
3254 &focus_handle,
3255 window,
3256 cx,
3257 )
3258 .map(|kb| kb.size(rems_from_px(10.))),
3259 )
3260 .on_click(cx.listener(|this, _, window, cx| {
3261 this.continue_conversation(window, cx);
3262 })),
3263 )
3264 .when(model.supports_burn_mode(), |this| {
3265 this.child(
3266 Button::new("continue-burn-mode", "Continue with Burn Mode")
3267 .style(ButtonStyle::Filled)
3268 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3269 .layer(ElevationIndex::ModalSurface)
3270 .label_size(LabelSize::Small)
3271 .key_binding(
3272 KeyBinding::for_action_in(
3273 &ContinueWithBurnMode,
3274 &focus_handle,
3275 window,
3276 cx,
3277 )
3278 .map(|kb| kb.size(rems_from_px(10.))),
3279 )
3280 .tooltip(Tooltip::text("Enable Burn Mode for unlimited tool use."))
3281 .on_click({
3282 let active_thread = active_thread.clone();
3283 cx.listener(move |this, _, window, cx| {
3284 active_thread.update(cx, |active_thread, cx| {
3285 active_thread.thread().update(cx, |thread, _cx| {
3286 thread.set_completion_mode(CompletionMode::Burn);
3287 });
3288 });
3289 this.continue_conversation(window, cx);
3290 })
3291 }),
3292 )
3293 }),
3294 );
3295
3296 Some(div().px_2().pb_2().child(banner).into_any_element())
3297 }
3298
3299 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3300 let message = message.into();
3301
3302 IconButton::new("copy", IconName::Copy)
3303 .icon_size(IconSize::Small)
3304 .icon_color(Color::Muted)
3305 .tooltip(Tooltip::text("Copy Error Message"))
3306 .on_click(move |_, _, cx| {
3307 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3308 })
3309 }
3310
3311 fn dismiss_error_button(
3312 &self,
3313 thread: &Entity<ActiveThread>,
3314 cx: &mut Context<Self>,
3315 ) -> impl IntoElement {
3316 IconButton::new("dismiss", IconName::Close)
3317 .icon_size(IconSize::Small)
3318 .icon_color(Color::Muted)
3319 .tooltip(Tooltip::text("Dismiss Error"))
3320 .on_click(cx.listener({
3321 let thread = thread.clone();
3322 move |_, _, _, cx| {
3323 thread.update(cx, |this, _cx| {
3324 this.clear_last_error();
3325 });
3326
3327 cx.notify();
3328 }
3329 }))
3330 }
3331
3332 fn upgrade_button(
3333 &self,
3334 thread: &Entity<ActiveThread>,
3335 cx: &mut Context<Self>,
3336 ) -> impl IntoElement {
3337 Button::new("upgrade", "Upgrade")
3338 .label_size(LabelSize::Small)
3339 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3340 .on_click(cx.listener({
3341 let thread = thread.clone();
3342 move |_, _, _, cx| {
3343 thread.update(cx, |this, _cx| {
3344 this.clear_last_error();
3345 });
3346
3347 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3348 cx.notify();
3349 }
3350 }))
3351 }
3352
3353 fn render_payment_required_error(
3354 &self,
3355 thread: &Entity<ActiveThread>,
3356 cx: &mut Context<Self>,
3357 ) -> AnyElement {
3358 const ERROR_MESSAGE: &str =
3359 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3360
3361 Callout::new()
3362 .severity(Severity::Error)
3363 .icon(IconName::XCircle)
3364 .title("Free Usage Exceeded")
3365 .description(ERROR_MESSAGE)
3366 .actions_slot(
3367 h_flex()
3368 .gap_0p5()
3369 .child(self.upgrade_button(thread, cx))
3370 .child(self.create_copy_button(ERROR_MESSAGE)),
3371 )
3372 .dismiss_action(self.dismiss_error_button(thread, cx))
3373 .into_any_element()
3374 }
3375
3376 fn render_model_request_limit_reached_error(
3377 &self,
3378 plan: Plan,
3379 thread: &Entity<ActiveThread>,
3380 cx: &mut Context<Self>,
3381 ) -> AnyElement {
3382 let error_message = match plan {
3383 Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3384 Plan::ZedProTrial | Plan::ZedFree => "Upgrade to Zed Pro for more prompts.",
3385 };
3386
3387 Callout::new()
3388 .severity(Severity::Error)
3389 .title("Model Prompt Limit Reached")
3390 .description(error_message)
3391 .actions_slot(
3392 h_flex()
3393 .gap_0p5()
3394 .child(self.upgrade_button(thread, cx))
3395 .child(self.create_copy_button(error_message)),
3396 )
3397 .dismiss_action(self.dismiss_error_button(thread, cx))
3398 .into_any_element()
3399 }
3400
3401 fn render_retry_button(&self, thread: &Entity<ActiveThread>) -> AnyElement {
3402 Button::new("retry", "Retry")
3403 .icon(IconName::RotateCw)
3404 .icon_position(IconPosition::Start)
3405 .icon_size(IconSize::Small)
3406 .label_size(LabelSize::Small)
3407 .on_click({
3408 let thread = thread.clone();
3409 move |_, window, cx| {
3410 thread.update(cx, |thread, cx| {
3411 thread.clear_last_error();
3412 thread.thread().update(cx, |thread, cx| {
3413 thread.retry_last_completion(Some(window.window_handle()), cx);
3414 });
3415 });
3416 }
3417 })
3418 .into_any_element()
3419 }
3420
3421 fn render_error_message(
3422 &self,
3423 header: SharedString,
3424 message: SharedString,
3425 thread: &Entity<ActiveThread>,
3426 cx: &mut Context<Self>,
3427 ) -> AnyElement {
3428 let message_with_header = format!("{}\n{}", header, message);
3429
3430 Callout::new()
3431 .severity(Severity::Error)
3432 .icon(IconName::XCircle)
3433 .title(header)
3434 .description(message)
3435 .actions_slot(
3436 h_flex()
3437 .gap_0p5()
3438 .child(self.render_retry_button(thread))
3439 .child(self.create_copy_button(message_with_header)),
3440 )
3441 .dismiss_action(self.dismiss_error_button(thread, cx))
3442 .into_any_element()
3443 }
3444
3445 fn render_retryable_error(
3446 &self,
3447 message: SharedString,
3448 can_enable_burn_mode: bool,
3449 thread: &Entity<ActiveThread>,
3450 ) -> AnyElement {
3451 Callout::new()
3452 .severity(Severity::Error)
3453 .title("Error")
3454 .description(message)
3455 .actions_slot(
3456 h_flex()
3457 .gap_0p5()
3458 .when(can_enable_burn_mode, |this| {
3459 this.child(
3460 Button::new("enable_burn_retry", "Enable Burn Mode and Retry")
3461 .icon(IconName::ZedBurnMode)
3462 .icon_position(IconPosition::Start)
3463 .icon_size(IconSize::Small)
3464 .label_size(LabelSize::Small)
3465 .on_click({
3466 let thread = thread.clone();
3467 move |_, window, cx| {
3468 thread.update(cx, |thread, cx| {
3469 thread.clear_last_error();
3470 thread.thread().update(cx, |thread, cx| {
3471 thread.enable_burn_mode_and_retry(
3472 Some(window.window_handle()),
3473 cx,
3474 );
3475 });
3476 });
3477 }
3478 }),
3479 )
3480 })
3481 .child(self.render_retry_button(thread)),
3482 )
3483 .into_any_element()
3484 }
3485
3486 fn render_prompt_editor(
3487 &self,
3488 context_editor: &Entity<TextThreadEditor>,
3489 buffer_search_bar: &Entity<BufferSearchBar>,
3490 window: &mut Window,
3491 cx: &mut Context<Self>,
3492 ) -> Div {
3493 let mut registrar = buffer_search::DivRegistrar::new(
3494 |this, _, _cx| match &this.active_view {
3495 ActiveView::TextThread {
3496 buffer_search_bar, ..
3497 } => Some(buffer_search_bar.clone()),
3498 _ => None,
3499 },
3500 cx,
3501 );
3502 BufferSearchBar::register(&mut registrar);
3503 registrar
3504 .into_div()
3505 .size_full()
3506 .relative()
3507 .map(|parent| {
3508 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
3509 if buffer_search_bar.is_dismissed() {
3510 return parent;
3511 }
3512 parent.child(
3513 div()
3514 .p(DynamicSpacing::Base08.rems(cx))
3515 .border_b_1()
3516 .border_color(cx.theme().colors().border_variant)
3517 .bg(cx.theme().colors().editor_background)
3518 .child(buffer_search_bar.render(window, cx)),
3519 )
3520 })
3521 })
3522 .child(context_editor.clone())
3523 .child(self.render_drag_target(cx))
3524 }
3525
3526 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
3527 let is_local = self.project.read(cx).is_local();
3528 div()
3529 .invisible()
3530 .absolute()
3531 .top_0()
3532 .right_0()
3533 .bottom_0()
3534 .left_0()
3535 .bg(cx.theme().colors().drop_target_background)
3536 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
3537 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
3538 .when(is_local, |this| {
3539 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
3540 })
3541 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
3542 let item = tab.pane.read(cx).item_for_index(tab.ix);
3543 let project_paths = item
3544 .and_then(|item| item.project_path(cx))
3545 .into_iter()
3546 .collect::<Vec<_>>();
3547 this.handle_drop(project_paths, vec![], window, cx);
3548 }))
3549 .on_drop(
3550 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
3551 let project_paths = selection
3552 .items()
3553 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
3554 .collect::<Vec<_>>();
3555 this.handle_drop(project_paths, vec![], window, cx);
3556 }),
3557 )
3558 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
3559 let tasks = paths
3560 .paths()
3561 .iter()
3562 .map(|path| {
3563 Workspace::project_path_for_path(this.project.clone(), path, false, cx)
3564 })
3565 .collect::<Vec<_>>();
3566 cx.spawn_in(window, async move |this, cx| {
3567 let mut paths = vec![];
3568 let mut added_worktrees = vec![];
3569 let opened_paths = futures::future::join_all(tasks).await;
3570 for entry in opened_paths {
3571 if let Some((worktree, project_path)) = entry.log_err() {
3572 added_worktrees.push(worktree);
3573 paths.push(project_path);
3574 }
3575 }
3576 this.update_in(cx, |this, window, cx| {
3577 this.handle_drop(paths, added_worktrees, window, cx);
3578 })
3579 .ok();
3580 })
3581 .detach();
3582 }))
3583 }
3584
3585 fn handle_drop(
3586 &mut self,
3587 paths: Vec<ProjectPath>,
3588 added_worktrees: Vec<Entity<Worktree>>,
3589 window: &mut Window,
3590 cx: &mut Context<Self>,
3591 ) {
3592 match &self.active_view {
3593 ActiveView::Thread { thread, .. } => {
3594 let context_store = thread.read(cx).context_store().clone();
3595 context_store.update(cx, move |context_store, cx| {
3596 let mut tasks = Vec::new();
3597 for project_path in &paths {
3598 tasks.push(context_store.add_file_from_path(
3599 project_path.clone(),
3600 false,
3601 cx,
3602 ));
3603 }
3604 cx.background_spawn(async move {
3605 futures::future::join_all(tasks).await;
3606 // Need to hold onto the worktrees until they have already been used when
3607 // opening the buffers.
3608 drop(added_worktrees);
3609 })
3610 .detach();
3611 });
3612 }
3613 ActiveView::ExternalAgentThread { thread_view } => {
3614 thread_view.update(cx, |thread_view, cx| {
3615 thread_view.insert_dragged_files(paths, added_worktrees, window, cx);
3616 });
3617 }
3618 ActiveView::TextThread { context_editor, .. } => {
3619 context_editor.update(cx, |context_editor, cx| {
3620 TextThreadEditor::insert_dragged_files(
3621 context_editor,
3622 paths,
3623 added_worktrees,
3624 window,
3625 cx,
3626 );
3627 });
3628 }
3629 ActiveView::History | ActiveView::Configuration => {}
3630 }
3631 }
3632
3633 fn key_context(&self) -> KeyContext {
3634 let mut key_context = KeyContext::new_with_defaults();
3635 key_context.add("AgentPanel");
3636 match &self.active_view {
3637 ActiveView::ExternalAgentThread { .. } => key_context.add("external_agent_thread"),
3638 ActiveView::TextThread { .. } => key_context.add("prompt_editor"),
3639 ActiveView::Thread { .. } | ActiveView::History | ActiveView::Configuration => {}
3640 }
3641 key_context
3642 }
3643}
3644
3645impl Render for AgentPanel {
3646 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3647 // WARNING: Changes to this element hierarchy can have
3648 // non-obvious implications to the layout of children.
3649 //
3650 // If you need to change it, please confirm:
3651 // - The message editor expands (cmd-option-esc) correctly
3652 // - When expanded, the buttons at the bottom of the panel are displayed correctly
3653 // - Font size works as expected and can be changed with cmd-+/cmd-
3654 // - Scrolling in all views works as expected
3655 // - Files can be dropped into the panel
3656 let content = v_flex()
3657 .relative()
3658 .size_full()
3659 .justify_between()
3660 .key_context(self.key_context())
3661 .on_action(cx.listener(Self::cancel))
3662 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
3663 this.new_thread(action, window, cx);
3664 }))
3665 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
3666 this.open_history(window, cx);
3667 }))
3668 .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
3669 this.open_configuration(window, cx);
3670 }))
3671 .on_action(cx.listener(Self::open_active_thread_as_markdown))
3672 .on_action(cx.listener(Self::deploy_rules_library))
3673 .on_action(cx.listener(Self::open_agent_diff))
3674 .on_action(cx.listener(Self::go_back))
3675 .on_action(cx.listener(Self::toggle_navigation_menu))
3676 .on_action(cx.listener(Self::toggle_options_menu))
3677 .on_action(cx.listener(Self::increase_font_size))
3678 .on_action(cx.listener(Self::decrease_font_size))
3679 .on_action(cx.listener(Self::reset_font_size))
3680 .on_action(cx.listener(Self::toggle_zoom))
3681 .on_action(cx.listener(|this, _: &ContinueThread, window, cx| {
3682 this.continue_conversation(window, cx);
3683 }))
3684 .on_action(cx.listener(|this, _: &ContinueWithBurnMode, window, cx| {
3685 match &this.active_view {
3686 ActiveView::Thread { thread, .. } => {
3687 thread.update(cx, |active_thread, cx| {
3688 active_thread.thread().update(cx, |thread, _cx| {
3689 thread.set_completion_mode(CompletionMode::Burn);
3690 });
3691 });
3692 this.continue_conversation(window, cx);
3693 }
3694 ActiveView::ExternalAgentThread { .. } => {}
3695 ActiveView::TextThread { .. }
3696 | ActiveView::History
3697 | ActiveView::Configuration => {}
3698 }
3699 }))
3700 .on_action(cx.listener(Self::toggle_burn_mode))
3701 .child(self.render_toolbar(window, cx))
3702 .children(self.render_onboarding(window, cx))
3703 .map(|parent| match &self.active_view {
3704 ActiveView::Thread {
3705 thread,
3706 message_editor,
3707 ..
3708 } => parent
3709 .child(
3710 if thread.read(cx).is_empty() && !self.should_render_onboarding(cx) {
3711 self.render_thread_empty_state(window, cx)
3712 .into_any_element()
3713 } else {
3714 thread.clone().into_any_element()
3715 },
3716 )
3717 .children(self.render_tool_use_limit_reached(window, cx))
3718 .when_some(thread.read(cx).last_error(), |this, last_error| {
3719 this.child(
3720 div()
3721 .child(match last_error {
3722 ThreadError::PaymentRequired => {
3723 self.render_payment_required_error(thread, cx)
3724 }
3725 ThreadError::ModelRequestLimitReached { plan } => self
3726 .render_model_request_limit_reached_error(plan, thread, cx),
3727 ThreadError::Message { header, message } => {
3728 self.render_error_message(header, message, thread, cx)
3729 }
3730 ThreadError::RetryableError {
3731 message,
3732 can_enable_burn_mode,
3733 } => self.render_retryable_error(
3734 message,
3735 can_enable_burn_mode,
3736 thread,
3737 ),
3738 })
3739 .into_any(),
3740 )
3741 })
3742 .child(h_flex().relative().child(message_editor.clone()).when(
3743 !LanguageModelRegistry::read_global(cx).has_authenticated_provider(cx),
3744 |this| this.child(self.render_backdrop(cx)),
3745 ))
3746 .child(self.render_drag_target(cx)),
3747 ActiveView::ExternalAgentThread { thread_view, .. } => parent
3748 .child(thread_view.clone())
3749 .child(self.render_drag_target(cx)),
3750 ActiveView::History => {
3751 if cx.has_flag::<feature_flags::GeminiAndNativeFeatureFlag>() {
3752 parent.child(self.acp_history.clone())
3753 } else {
3754 parent.child(self.history.clone())
3755 }
3756 }
3757 ActiveView::TextThread {
3758 context_editor,
3759 buffer_search_bar,
3760 ..
3761 } => {
3762 let model_registry = LanguageModelRegistry::read_global(cx);
3763 let configuration_error =
3764 model_registry.configuration_error(model_registry.default_model(), cx);
3765 parent
3766 .map(|this| {
3767 if !self.should_render_onboarding(cx)
3768 && let Some(err) = configuration_error.as_ref()
3769 {
3770 this.child(self.render_configuration_error(
3771 true,
3772 err,
3773 &self.focus_handle(cx),
3774 window,
3775 cx,
3776 ))
3777 } else {
3778 this
3779 }
3780 })
3781 .child(self.render_prompt_editor(
3782 context_editor,
3783 buffer_search_bar,
3784 window,
3785 cx,
3786 ))
3787 }
3788 ActiveView::Configuration => parent.children(self.configuration.clone()),
3789 })
3790 .children(self.render_trial_end_upsell(window, cx));
3791
3792 match self.active_view.which_font_size_used() {
3793 WhichFontSize::AgentFont => {
3794 WithRemSize::new(ThemeSettings::get_global(cx).agent_font_size(cx))
3795 .size_full()
3796 .child(content)
3797 .into_any()
3798 }
3799 _ => content.into_any(),
3800 }
3801 }
3802}
3803
3804struct PromptLibraryInlineAssist {
3805 workspace: WeakEntity<Workspace>,
3806}
3807
3808impl PromptLibraryInlineAssist {
3809 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
3810 Self { workspace }
3811 }
3812}
3813
3814impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
3815 fn assist(
3816 &self,
3817 prompt_editor: &Entity<Editor>,
3818 initial_prompt: Option<String>,
3819 window: &mut Window,
3820 cx: &mut Context<RulesLibrary>,
3821 ) {
3822 InlineAssistant::update_global(cx, |assistant, cx| {
3823 let Some(project) = self
3824 .workspace
3825 .upgrade()
3826 .map(|workspace| workspace.read(cx).project().downgrade())
3827 else {
3828 return;
3829 };
3830 let prompt_store = None;
3831 let thread_store = None;
3832 let text_thread_store = None;
3833 let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
3834 assistant.assist(
3835 prompt_editor,
3836 self.workspace.clone(),
3837 context_store,
3838 project,
3839 prompt_store,
3840 thread_store,
3841 text_thread_store,
3842 initial_prompt,
3843 window,
3844 cx,
3845 )
3846 })
3847 }
3848
3849 fn focus_agent_panel(
3850 &self,
3851 workspace: &mut Workspace,
3852 window: &mut Window,
3853 cx: &mut Context<Workspace>,
3854 ) -> bool {
3855 workspace.focus_panel::<AgentPanel>(window, cx).is_some()
3856 }
3857}
3858
3859pub struct ConcreteAssistantPanelDelegate;
3860
3861impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
3862 fn active_context_editor(
3863 &self,
3864 workspace: &mut Workspace,
3865 _window: &mut Window,
3866 cx: &mut Context<Workspace>,
3867 ) -> Option<Entity<TextThreadEditor>> {
3868 let panel = workspace.panel::<AgentPanel>(cx)?;
3869 panel.read(cx).active_context_editor()
3870 }
3871
3872 fn open_saved_context(
3873 &self,
3874 workspace: &mut Workspace,
3875 path: Arc<Path>,
3876 window: &mut Window,
3877 cx: &mut Context<Workspace>,
3878 ) -> Task<Result<()>> {
3879 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3880 return Task::ready(Err(anyhow!("Agent panel not found")));
3881 };
3882
3883 panel.update(cx, |panel, cx| {
3884 panel.open_saved_prompt_editor(path, window, cx)
3885 })
3886 }
3887
3888 fn open_remote_context(
3889 &self,
3890 _workspace: &mut Workspace,
3891 _context_id: assistant_context::ContextId,
3892 _window: &mut Window,
3893 _cx: &mut Context<Workspace>,
3894 ) -> Task<Result<Entity<TextThreadEditor>>> {
3895 Task::ready(Err(anyhow!("opening remote context not implemented")))
3896 }
3897
3898 fn quote_selection(
3899 &self,
3900 workspace: &mut Workspace,
3901 selection_ranges: Vec<Range<Anchor>>,
3902 buffer: Entity<MultiBuffer>,
3903 window: &mut Window,
3904 cx: &mut Context<Workspace>,
3905 ) {
3906 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3907 return;
3908 };
3909
3910 if !panel.focus_handle(cx).contains_focused(window, cx) {
3911 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
3912 }
3913
3914 panel.update(cx, |_, cx| {
3915 // Wait to create a new context until the workspace is no longer
3916 // being updated.
3917 cx.defer_in(window, move |panel, window, cx| {
3918 if let Some(thread_view) = panel.active_thread_view() {
3919 thread_view.update(cx, |thread_view, cx| {
3920 thread_view.insert_selections(window, cx);
3921 });
3922 } else if let Some(message_editor) = panel.active_message_editor() {
3923 message_editor.update(cx, |message_editor, cx| {
3924 message_editor.context_store().update(cx, |store, cx| {
3925 let buffer = buffer.read(cx);
3926 let selection_ranges = selection_ranges
3927 .into_iter()
3928 .flat_map(|range| {
3929 let (start_buffer, start) =
3930 buffer.text_anchor_for_position(range.start, cx)?;
3931 let (end_buffer, end) =
3932 buffer.text_anchor_for_position(range.end, cx)?;
3933 if start_buffer != end_buffer {
3934 return None;
3935 }
3936 Some((start_buffer, start..end))
3937 })
3938 .collect::<Vec<_>>();
3939
3940 for (buffer, range) in selection_ranges {
3941 store.add_selection(buffer, range, cx);
3942 }
3943 })
3944 })
3945 } else if let Some(context_editor) = panel.active_context_editor() {
3946 let snapshot = buffer.read(cx).snapshot(cx);
3947 let selection_ranges = selection_ranges
3948 .into_iter()
3949 .map(|range| range.to_point(&snapshot))
3950 .collect::<Vec<_>>();
3951
3952 context_editor.update(cx, |context_editor, cx| {
3953 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
3954 });
3955 }
3956 });
3957 });
3958 }
3959}
3960
3961struct OnboardingUpsell;
3962
3963impl Dismissable for OnboardingUpsell {
3964 const KEY: &'static str = "dismissed-trial-upsell";
3965}
3966
3967struct TrialEndUpsell;
3968
3969impl Dismissable for TrialEndUpsell {
3970 const KEY: &'static str = "dismissed-trial-end-upsell";
3971}