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