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 let mut old_acp_thread = None;
1475
1476 match &self.active_view {
1477 ActiveView::Thread { thread, .. } => {
1478 let thread = thread.read(cx);
1479 if thread.is_empty() {
1480 let id = thread.thread().read(cx).id().clone();
1481 self.history_store.update(cx, |store, cx| {
1482 store.remove_recently_opened_thread(id, cx);
1483 });
1484 }
1485 }
1486 ActiveView::ExternalAgentThread { thread_view } => {
1487 old_acp_thread.replace(thread_view.downgrade());
1488 }
1489 _ => {}
1490 }
1491
1492 match &new_view {
1493 ActiveView::Thread { thread, .. } => self.history_store.update(cx, |store, cx| {
1494 let id = thread.read(cx).thread().read(cx).id().clone();
1495 store.push_recently_opened_entry(HistoryEntryId::Thread(id), cx);
1496 }),
1497 ActiveView::TextThread { context_editor, .. } => {
1498 self.history_store.update(cx, |store, cx| {
1499 if let Some(path) = context_editor.read(cx).context().read(cx).path() {
1500 store.push_recently_opened_entry(HistoryEntryId::Context(path.clone()), cx)
1501 }
1502 })
1503 }
1504 ActiveView::ExternalAgentThread { .. } => {}
1505 ActiveView::History | ActiveView::Configuration => {}
1506 }
1507
1508 if current_is_special && !new_is_special {
1509 self.active_view = new_view;
1510 } else if !current_is_special && new_is_special {
1511 self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
1512 } else {
1513 if !new_is_special {
1514 self.previous_view = None;
1515 }
1516 self.active_view = new_view;
1517 }
1518
1519 debug_assert!(
1520 old_acp_thread.map_or(true, |thread| !thread.is_upgradable()),
1521 "AcpThreadView leaked"
1522 );
1523
1524 self.acp_message_history.borrow_mut().reset_position();
1525
1526 self.focus_handle(cx).focus(window);
1527 }
1528
1529 fn populate_recently_opened_menu_section(
1530 mut menu: ContextMenu,
1531 panel: Entity<Self>,
1532 cx: &mut Context<ContextMenu>,
1533 ) -> ContextMenu {
1534 let entries = panel
1535 .read(cx)
1536 .history_store
1537 .read(cx)
1538 .recently_opened_entries(cx);
1539
1540 if entries.is_empty() {
1541 return menu;
1542 }
1543
1544 menu = menu.header("Recently Opened");
1545
1546 for entry in entries {
1547 let title = entry.title().clone();
1548 let id = entry.id();
1549
1550 menu = menu.entry_with_end_slot_on_hover(
1551 title,
1552 None,
1553 {
1554 let panel = panel.downgrade();
1555 let id = id.clone();
1556 move |window, cx| {
1557 let id = id.clone();
1558 panel
1559 .update(cx, move |this, cx| match id {
1560 HistoryEntryId::Thread(id) => this
1561 .open_thread_by_id(&id, window, cx)
1562 .detach_and_log_err(cx),
1563 HistoryEntryId::Context(path) => this
1564 .open_saved_prompt_editor(path.clone(), window, cx)
1565 .detach_and_log_err(cx),
1566 })
1567 .ok();
1568 }
1569 },
1570 IconName::Close,
1571 "Close Entry".into(),
1572 {
1573 let panel = panel.downgrade();
1574 let id = id.clone();
1575 move |_window, cx| {
1576 panel
1577 .update(cx, |this, cx| {
1578 this.history_store.update(cx, |history_store, cx| {
1579 history_store.remove_recently_opened_entry(&id, cx);
1580 });
1581 })
1582 .ok();
1583 }
1584 },
1585 );
1586 }
1587
1588 menu = menu.separator();
1589
1590 menu
1591 }
1592}
1593
1594impl Focusable for AgentPanel {
1595 fn focus_handle(&self, cx: &App) -> FocusHandle {
1596 match &self.active_view {
1597 ActiveView::Thread { message_editor, .. } => message_editor.focus_handle(cx),
1598 ActiveView::ExternalAgentThread { thread_view, .. } => thread_view.focus_handle(cx),
1599 ActiveView::History => self.history.focus_handle(cx),
1600 ActiveView::TextThread { context_editor, .. } => context_editor.focus_handle(cx),
1601 ActiveView::Configuration => {
1602 if let Some(configuration) = self.configuration.as_ref() {
1603 configuration.focus_handle(cx)
1604 } else {
1605 cx.focus_handle()
1606 }
1607 }
1608 }
1609 }
1610}
1611
1612fn agent_panel_dock_position(cx: &App) -> DockPosition {
1613 match AgentSettings::get_global(cx).dock {
1614 AgentDockPosition::Left => DockPosition::Left,
1615 AgentDockPosition::Bottom => DockPosition::Bottom,
1616 AgentDockPosition::Right => DockPosition::Right,
1617 }
1618}
1619
1620impl EventEmitter<PanelEvent> for AgentPanel {}
1621
1622impl Panel for AgentPanel {
1623 fn persistent_name() -> &'static str {
1624 "AgentPanel"
1625 }
1626
1627 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1628 agent_panel_dock_position(cx)
1629 }
1630
1631 fn position_is_valid(&self, position: DockPosition) -> bool {
1632 position != DockPosition::Bottom
1633 }
1634
1635 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1636 settings::update_settings_file::<AgentSettings>(self.fs.clone(), cx, move |settings, _| {
1637 let dock = match position {
1638 DockPosition::Left => AgentDockPosition::Left,
1639 DockPosition::Bottom => AgentDockPosition::Bottom,
1640 DockPosition::Right => AgentDockPosition::Right,
1641 };
1642 settings.set_dock(dock);
1643 });
1644 }
1645
1646 fn size(&self, window: &Window, cx: &App) -> Pixels {
1647 let settings = AgentSettings::get_global(cx);
1648 match self.position(window, cx) {
1649 DockPosition::Left | DockPosition::Right => {
1650 self.width.unwrap_or(settings.default_width)
1651 }
1652 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1653 }
1654 }
1655
1656 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1657 match self.position(window, cx) {
1658 DockPosition::Left | DockPosition::Right => self.width = size,
1659 DockPosition::Bottom => self.height = size,
1660 }
1661 self.serialize(cx);
1662 cx.notify();
1663 }
1664
1665 fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
1666
1667 fn remote_id() -> Option<proto::PanelId> {
1668 Some(proto::PanelId::AssistantPanel)
1669 }
1670
1671 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1672 (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
1673 }
1674
1675 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1676 Some("Agent Panel")
1677 }
1678
1679 fn toggle_action(&self) -> Box<dyn Action> {
1680 Box::new(ToggleFocus)
1681 }
1682
1683 fn activation_priority(&self) -> u32 {
1684 3
1685 }
1686
1687 fn enabled(&self, cx: &App) -> bool {
1688 DisableAiSettings::get_global(cx).disable_ai.not() && AgentSettings::get_global(cx).enabled
1689 }
1690
1691 fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1692 self.zoomed
1693 }
1694
1695 fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1696 self.zoomed = zoomed;
1697 cx.notify();
1698 }
1699}
1700
1701impl AgentPanel {
1702 fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
1703 const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
1704
1705 let content = match &self.active_view {
1706 ActiveView::Thread {
1707 thread: active_thread,
1708 change_title_editor,
1709 ..
1710 } => {
1711 let state = {
1712 let active_thread = active_thread.read(cx);
1713 if active_thread.is_empty() {
1714 &ThreadSummary::Pending
1715 } else {
1716 active_thread.summary(cx)
1717 }
1718 };
1719
1720 match state {
1721 ThreadSummary::Pending => Label::new(ThreadSummary::DEFAULT.clone())
1722 .truncate()
1723 .into_any_element(),
1724 ThreadSummary::Generating => Label::new(LOADING_SUMMARY_PLACEHOLDER)
1725 .truncate()
1726 .into_any_element(),
1727 ThreadSummary::Ready(_) => div()
1728 .w_full()
1729 .child(change_title_editor.clone())
1730 .into_any_element(),
1731 ThreadSummary::Error => h_flex()
1732 .w_full()
1733 .child(change_title_editor.clone())
1734 .child(
1735 ui::IconButton::new("retry-summary-generation", IconName::RotateCcw)
1736 .on_click({
1737 let active_thread = active_thread.clone();
1738 move |_, _window, cx| {
1739 active_thread.update(cx, |thread, cx| {
1740 thread.regenerate_summary(cx);
1741 });
1742 }
1743 })
1744 .tooltip(move |_window, cx| {
1745 cx.new(|_| {
1746 Tooltip::new("Failed to generate title")
1747 .meta("Click to try again")
1748 })
1749 .into()
1750 }),
1751 )
1752 .into_any_element(),
1753 }
1754 }
1755 ActiveView::ExternalAgentThread { thread_view } => {
1756 Label::new(thread_view.read(cx).title(cx))
1757 .truncate()
1758 .into_any_element()
1759 }
1760 ActiveView::TextThread {
1761 title_editor,
1762 context_editor,
1763 ..
1764 } => {
1765 let summary = context_editor.read(cx).context().read(cx).summary();
1766
1767 match summary {
1768 ContextSummary::Pending => Label::new(ContextSummary::DEFAULT)
1769 .truncate()
1770 .into_any_element(),
1771 ContextSummary::Content(summary) => {
1772 if summary.done {
1773 div()
1774 .w_full()
1775 .child(title_editor.clone())
1776 .into_any_element()
1777 } else {
1778 Label::new(LOADING_SUMMARY_PLACEHOLDER)
1779 .truncate()
1780 .into_any_element()
1781 }
1782 }
1783 ContextSummary::Error => h_flex()
1784 .w_full()
1785 .child(title_editor.clone())
1786 .child(
1787 ui::IconButton::new("retry-summary-generation", IconName::RotateCcw)
1788 .on_click({
1789 let context_editor = context_editor.clone();
1790 move |_, _window, cx| {
1791 context_editor.update(cx, |context_editor, cx| {
1792 context_editor.regenerate_summary(cx);
1793 });
1794 }
1795 })
1796 .tooltip(move |_window, cx| {
1797 cx.new(|_| {
1798 Tooltip::new("Failed to generate title")
1799 .meta("Click to try again")
1800 })
1801 .into()
1802 }),
1803 )
1804 .into_any_element(),
1805 }
1806 }
1807 ActiveView::History => Label::new("History").truncate().into_any_element(),
1808 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
1809 };
1810
1811 h_flex()
1812 .key_context("TitleEditor")
1813 .id("TitleEditor")
1814 .flex_grow()
1815 .w_full()
1816 .max_w_full()
1817 .overflow_x_scroll()
1818 .child(content)
1819 .into_any()
1820 }
1821
1822 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1823 let user_store = self.user_store.read(cx);
1824 let usage = user_store.model_request_usage();
1825
1826 let account_url = zed_urls::account_url(cx);
1827
1828 let focus_handle = self.focus_handle(cx);
1829
1830 let go_back_button = div().child(
1831 IconButton::new("go-back", IconName::ArrowLeft)
1832 .icon_size(IconSize::Small)
1833 .on_click(cx.listener(|this, _, window, cx| {
1834 this.go_back(&workspace::GoBack, window, cx);
1835 }))
1836 .tooltip({
1837 let focus_handle = focus_handle.clone();
1838 move |window, cx| {
1839 Tooltip::for_action_in(
1840 "Go Back",
1841 &workspace::GoBack,
1842 &focus_handle,
1843 window,
1844 cx,
1845 )
1846 }
1847 }),
1848 );
1849
1850 let recent_entries_menu = div().child(
1851 PopoverMenu::new("agent-nav-menu")
1852 .trigger_with_tooltip(
1853 IconButton::new("agent-nav-menu", IconName::MenuAlt)
1854 .icon_size(IconSize::Small)
1855 .style(ui::ButtonStyle::Subtle),
1856 {
1857 let focus_handle = focus_handle.clone();
1858 move |window, cx| {
1859 Tooltip::for_action_in(
1860 "Toggle Panel Menu",
1861 &ToggleNavigationMenu,
1862 &focus_handle,
1863 window,
1864 cx,
1865 )
1866 }
1867 },
1868 )
1869 .anchor(Corner::TopLeft)
1870 .with_handle(self.assistant_navigation_menu_handle.clone())
1871 .menu({
1872 let menu = self.assistant_navigation_menu.clone();
1873 move |window, cx| {
1874 if let Some(menu) = menu.as_ref() {
1875 menu.update(cx, |_, cx| {
1876 cx.defer_in(window, |menu, window, cx| {
1877 menu.rebuild(window, cx);
1878 });
1879 })
1880 }
1881 menu.clone()
1882 }
1883 }),
1884 );
1885
1886 let full_screen_label = if self.is_zoomed(window, cx) {
1887 "Disable Full Screen"
1888 } else {
1889 "Enable Full Screen"
1890 };
1891
1892 let active_thread = match &self.active_view {
1893 ActiveView::Thread { thread, .. } => Some(thread.read(cx).thread().clone()),
1894 ActiveView::ExternalAgentThread { .. }
1895 | ActiveView::TextThread { .. }
1896 | ActiveView::History
1897 | ActiveView::Configuration => None,
1898 };
1899
1900 let new_thread_menu = PopoverMenu::new("new_thread_menu")
1901 .trigger_with_tooltip(
1902 IconButton::new("new_thread_menu_btn", IconName::Plus).icon_size(IconSize::Small),
1903 Tooltip::text("New Thread…"),
1904 )
1905 .anchor(Corner::TopRight)
1906 .with_handle(self.new_thread_menu_handle.clone())
1907 .menu({
1908 let focus_handle = focus_handle.clone();
1909 move |window, cx| {
1910 let active_thread = active_thread.clone();
1911 Some(ContextMenu::build(window, cx, |mut menu, _window, cx| {
1912 menu = menu
1913 .context(focus_handle.clone())
1914 .when(cx.has_flag::<feature_flags::AcpFeatureFlag>(), |this| {
1915 this.header("Zed Agent")
1916 })
1917 .when_some(active_thread, |this, active_thread| {
1918 let thread = active_thread.read(cx);
1919
1920 if !thread.is_empty() {
1921 let thread_id = thread.id().clone();
1922 this.item(
1923 ContextMenuEntry::new("New From Summary")
1924 .icon(IconName::ThreadFromSummary)
1925 .icon_color(Color::Muted)
1926 .handler(move |window, cx| {
1927 window.dispatch_action(
1928 Box::new(NewThread {
1929 from_thread_id: Some(thread_id.clone()),
1930 }),
1931 cx,
1932 );
1933 }),
1934 )
1935 } else {
1936 this
1937 }
1938 })
1939 .item(
1940 ContextMenuEntry::new("New Thread")
1941 .icon(IconName::Thread)
1942 .icon_color(Color::Muted)
1943 .action(NewThread::default().boxed_clone())
1944 .handler(move |window, cx| {
1945 window.dispatch_action(
1946 NewThread::default().boxed_clone(),
1947 cx,
1948 );
1949 }),
1950 )
1951 .item(
1952 ContextMenuEntry::new("New Text Thread")
1953 .icon(IconName::TextThread)
1954 .icon_color(Color::Muted)
1955 .action(NewTextThread.boxed_clone())
1956 .handler(move |window, cx| {
1957 window.dispatch_action(NewTextThread.boxed_clone(), cx);
1958 }),
1959 )
1960 .when(cx.has_flag::<feature_flags::AcpFeatureFlag>(), |this| {
1961 this.separator()
1962 .header("External Agents")
1963 .item(
1964 ContextMenuEntry::new("New Gemini Thread")
1965 .icon(IconName::AiGemini)
1966 .icon_color(Color::Muted)
1967 .handler(move |window, cx| {
1968 window.dispatch_action(
1969 NewExternalAgentThread {
1970 agent: Some(crate::ExternalAgent::Gemini),
1971 }
1972 .boxed_clone(),
1973 cx,
1974 );
1975 }),
1976 )
1977 .item(
1978 ContextMenuEntry::new("New Claude Code Thread")
1979 .icon(IconName::AiClaude)
1980 .icon_color(Color::Muted)
1981 .handler(move |window, cx| {
1982 window.dispatch_action(
1983 NewExternalAgentThread {
1984 agent: Some(
1985 crate::ExternalAgent::ClaudeCode,
1986 ),
1987 }
1988 .boxed_clone(),
1989 cx,
1990 );
1991 }),
1992 )
1993 });
1994 menu
1995 }))
1996 }
1997 });
1998
1999 let agent_panel_menu = PopoverMenu::new("agent-options-menu")
2000 .trigger_with_tooltip(
2001 IconButton::new("agent-options-menu", IconName::Ellipsis)
2002 .icon_size(IconSize::Small),
2003 {
2004 let focus_handle = focus_handle.clone();
2005 move |window, cx| {
2006 Tooltip::for_action_in(
2007 "Toggle Agent Menu",
2008 &ToggleOptionsMenu,
2009 &focus_handle,
2010 window,
2011 cx,
2012 )
2013 }
2014 },
2015 )
2016 .anchor(Corner::TopRight)
2017 .with_handle(self.agent_panel_menu_handle.clone())
2018 .menu({
2019 let focus_handle = focus_handle.clone();
2020 move |window, cx| {
2021 Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
2022 menu = menu.context(focus_handle.clone());
2023 if let Some(usage) = usage {
2024 menu = menu
2025 .header_with_link("Prompt Usage", "Manage", account_url.clone())
2026 .custom_entry(
2027 move |_window, cx| {
2028 let used_percentage = match usage.limit {
2029 UsageLimit::Limited(limit) => {
2030 Some((usage.amount as f32 / limit as f32) * 100.)
2031 }
2032 UsageLimit::Unlimited => None,
2033 };
2034
2035 h_flex()
2036 .flex_1()
2037 .gap_1p5()
2038 .children(used_percentage.map(|percent| {
2039 ProgressBar::new("usage", percent, 100., cx)
2040 }))
2041 .child(
2042 Label::new(match usage.limit {
2043 UsageLimit::Limited(limit) => {
2044 format!("{} / {limit}", usage.amount)
2045 }
2046 UsageLimit::Unlimited => {
2047 format!("{} / ∞", usage.amount)
2048 }
2049 })
2050 .size(LabelSize::Small)
2051 .color(Color::Muted),
2052 )
2053 .into_any_element()
2054 },
2055 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
2056 )
2057 .separator()
2058 }
2059
2060 menu = menu
2061 .header("MCP Servers")
2062 .action(
2063 "View Server Extensions",
2064 Box::new(zed_actions::Extensions {
2065 category_filter: Some(
2066 zed_actions::ExtensionCategoryFilter::ContextServers,
2067 ),
2068 id: None,
2069 }),
2070 )
2071 .action("Add Custom Server…", Box::new(AddContextServer))
2072 .separator();
2073
2074 menu = menu
2075 .action("Rules…", Box::new(OpenRulesLibrary::default()))
2076 .action("Settings", Box::new(OpenSettings))
2077 .separator()
2078 .action(full_screen_label, Box::new(ToggleZoom));
2079 menu
2080 }))
2081 }
2082 });
2083
2084 h_flex()
2085 .id("assistant-toolbar")
2086 .h(Tab::container_height(cx))
2087 .max_w_full()
2088 .flex_none()
2089 .justify_between()
2090 .gap_2()
2091 .bg(cx.theme().colors().tab_bar_background)
2092 .border_b_1()
2093 .border_color(cx.theme().colors().border)
2094 .child(
2095 h_flex()
2096 .size_full()
2097 .pl_1()
2098 .gap_1()
2099 .child(match &self.active_view {
2100 ActiveView::History | ActiveView::Configuration => go_back_button,
2101 _ => recent_entries_menu,
2102 })
2103 .child(self.render_title_view(window, cx)),
2104 )
2105 .child(
2106 h_flex()
2107 .h_full()
2108 .gap_2()
2109 .children(self.render_token_count(cx))
2110 .child(
2111 h_flex()
2112 .h_full()
2113 .gap(DynamicSpacing::Base02.rems(cx))
2114 .px(DynamicSpacing::Base08.rems(cx))
2115 .border_l_1()
2116 .border_color(cx.theme().colors().border)
2117 .child(new_thread_menu)
2118 .child(agent_panel_menu),
2119 ),
2120 )
2121 }
2122
2123 fn render_token_count(&self, cx: &App) -> Option<AnyElement> {
2124 match &self.active_view {
2125 ActiveView::Thread {
2126 thread,
2127 message_editor,
2128 ..
2129 } => {
2130 let active_thread = thread.read(cx);
2131 let message_editor = message_editor.read(cx);
2132
2133 let editor_empty = message_editor.is_editor_fully_empty(cx);
2134
2135 if active_thread.is_empty() && editor_empty {
2136 return None;
2137 }
2138
2139 let thread = active_thread.thread().read(cx);
2140 let is_generating = thread.is_generating();
2141 let conversation_token_usage = thread.total_token_usage()?;
2142
2143 let (total_token_usage, is_estimating) =
2144 if let Some((editing_message_id, unsent_tokens)) =
2145 active_thread.editing_message_id()
2146 {
2147 let combined = thread
2148 .token_usage_up_to_message(editing_message_id)
2149 .add(unsent_tokens);
2150
2151 (combined, unsent_tokens > 0)
2152 } else {
2153 let unsent_tokens =
2154 message_editor.last_estimated_token_count().unwrap_or(0);
2155 let combined = conversation_token_usage.add(unsent_tokens);
2156
2157 (combined, unsent_tokens > 0)
2158 };
2159
2160 let is_waiting_to_update_token_count =
2161 message_editor.is_waiting_to_update_token_count();
2162
2163 if total_token_usage.total == 0 {
2164 return None;
2165 }
2166
2167 let token_color = match total_token_usage.ratio() {
2168 TokenUsageRatio::Normal if is_estimating => Color::Default,
2169 TokenUsageRatio::Normal => Color::Muted,
2170 TokenUsageRatio::Warning => Color::Warning,
2171 TokenUsageRatio::Exceeded => Color::Error,
2172 };
2173
2174 let token_count = h_flex()
2175 .id("token-count")
2176 .flex_shrink_0()
2177 .gap_0p5()
2178 .when(!is_generating && is_estimating, |parent| {
2179 parent
2180 .child(
2181 h_flex()
2182 .mr_1()
2183 .size_2p5()
2184 .justify_center()
2185 .rounded_full()
2186 .bg(cx.theme().colors().text.opacity(0.1))
2187 .child(
2188 div().size_1().rounded_full().bg(cx.theme().colors().text),
2189 ),
2190 )
2191 .tooltip(move |window, cx| {
2192 Tooltip::with_meta(
2193 "Estimated New Token Count",
2194 None,
2195 format!(
2196 "Current Conversation Tokens: {}",
2197 humanize_token_count(conversation_token_usage.total)
2198 ),
2199 window,
2200 cx,
2201 )
2202 })
2203 })
2204 .child(
2205 Label::new(humanize_token_count(total_token_usage.total))
2206 .size(LabelSize::Small)
2207 .color(token_color)
2208 .map(|label| {
2209 if is_generating || is_waiting_to_update_token_count {
2210 label
2211 .with_animation(
2212 "used-tokens-label",
2213 Animation::new(Duration::from_secs(2))
2214 .repeat()
2215 .with_easing(pulsating_between(0.6, 1.)),
2216 |label, delta| label.alpha(delta),
2217 )
2218 .into_any()
2219 } else {
2220 label.into_any_element()
2221 }
2222 }),
2223 )
2224 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2225 .child(
2226 Label::new(humanize_token_count(total_token_usage.max))
2227 .size(LabelSize::Small)
2228 .color(Color::Muted),
2229 )
2230 .into_any();
2231
2232 Some(token_count)
2233 }
2234 ActiveView::TextThread { context_editor, .. } => {
2235 let element = render_remaining_tokens(context_editor, cx)?;
2236
2237 Some(element.into_any_element())
2238 }
2239 ActiveView::ExternalAgentThread { .. }
2240 | ActiveView::History
2241 | ActiveView::Configuration => {
2242 return None;
2243 }
2244 }
2245 }
2246
2247 fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
2248 if TrialEndUpsell::dismissed() {
2249 return false;
2250 }
2251
2252 match &self.active_view {
2253 ActiveView::Thread { thread, .. } => {
2254 if thread
2255 .read(cx)
2256 .thread()
2257 .read(cx)
2258 .configured_model()
2259 .map_or(false, |model| {
2260 model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2261 })
2262 {
2263 return false;
2264 }
2265 }
2266 ActiveView::TextThread { .. } => {
2267 if LanguageModelRegistry::global(cx)
2268 .read(cx)
2269 .default_model()
2270 .map_or(false, |model| {
2271 model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2272 })
2273 {
2274 return false;
2275 }
2276 }
2277 ActiveView::ExternalAgentThread { .. }
2278 | ActiveView::History
2279 | ActiveView::Configuration => return false,
2280 }
2281
2282 let plan = self.user_store.read(cx).plan();
2283 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2284
2285 matches!(plan, Some(Plan::ZedFree)) && has_previous_trial
2286 }
2287
2288 fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
2289 if OnboardingUpsell::dismissed() {
2290 return false;
2291 }
2292
2293 match &self.active_view {
2294 ActiveView::Thread { .. } | ActiveView::TextThread { .. } => {
2295 let history_is_empty = self
2296 .history_store
2297 .update(cx, |store, cx| store.recent_entries(1, cx).is_empty());
2298
2299 let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
2300 .providers()
2301 .iter()
2302 .any(|provider| {
2303 provider.is_authenticated(cx)
2304 && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2305 });
2306
2307 history_is_empty || !has_configured_non_zed_providers
2308 }
2309 ActiveView::ExternalAgentThread { .. }
2310 | ActiveView::History
2311 | ActiveView::Configuration => false,
2312 }
2313 }
2314
2315 fn render_onboarding(
2316 &self,
2317 _window: &mut Window,
2318 cx: &mut Context<Self>,
2319 ) -> Option<impl IntoElement> {
2320 if !self.should_render_onboarding(cx) {
2321 return None;
2322 }
2323
2324 let thread_view = matches!(&self.active_view, ActiveView::Thread { .. });
2325 let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
2326
2327 Some(
2328 div()
2329 .when(thread_view, |this| {
2330 this.size_full().bg(cx.theme().colors().panel_background)
2331 })
2332 .when(text_thread_view, |this| {
2333 this.bg(cx.theme().colors().editor_background)
2334 })
2335 .child(self.onboarding.clone()),
2336 )
2337 }
2338
2339 fn render_trial_end_upsell(
2340 &self,
2341 _window: &mut Window,
2342 cx: &mut Context<Self>,
2343 ) -> Option<impl IntoElement> {
2344 if !self.should_render_trial_end_upsell(cx) {
2345 return None;
2346 }
2347
2348 Some(EndTrialUpsell::new(Arc::new({
2349 let this = cx.entity();
2350 move |_, cx| {
2351 this.update(cx, |_this, cx| {
2352 TrialEndUpsell::set_dismissed(true, cx);
2353 cx.notify();
2354 });
2355 }
2356 })))
2357 }
2358
2359 fn render_empty_state_section_header(
2360 &self,
2361 label: impl Into<SharedString>,
2362 action_slot: Option<AnyElement>,
2363 cx: &mut Context<Self>,
2364 ) -> impl IntoElement {
2365 h_flex()
2366 .mt_2()
2367 .pl_1p5()
2368 .pb_1()
2369 .w_full()
2370 .justify_between()
2371 .border_b_1()
2372 .border_color(cx.theme().colors().border_variant)
2373 .child(
2374 Label::new(label.into())
2375 .size(LabelSize::Small)
2376 .color(Color::Muted),
2377 )
2378 .children(action_slot)
2379 }
2380
2381 fn render_thread_empty_state(
2382 &self,
2383 window: &mut Window,
2384 cx: &mut Context<Self>,
2385 ) -> impl IntoElement {
2386 let recent_history = self
2387 .history_store
2388 .update(cx, |this, cx| this.recent_entries(6, cx));
2389
2390 let model_registry = LanguageModelRegistry::read_global(cx);
2391
2392 let configuration_error =
2393 model_registry.configuration_error(model_registry.default_model(), cx);
2394
2395 let no_error = configuration_error.is_none();
2396 let focus_handle = self.focus_handle(cx);
2397
2398 v_flex()
2399 .size_full()
2400 .bg(cx.theme().colors().panel_background)
2401 .when(recent_history.is_empty(), |this| {
2402 this.child(
2403 v_flex()
2404 .size_full()
2405 .mx_auto()
2406 .justify_center()
2407 .items_center()
2408 .gap_1()
2409 .child(h_flex().child(Headline::new("Welcome to the Agent Panel")))
2410 .when(no_error, |parent| {
2411 parent
2412 .child(h_flex().child(
2413 Label::new("Ask and build anything.").color(Color::Muted),
2414 ))
2415 .child(
2416 v_flex()
2417 .mt_2()
2418 .gap_1()
2419 .max_w_48()
2420 .child(
2421 Button::new("context", "Add Context")
2422 .label_size(LabelSize::Small)
2423 .icon(IconName::FileCode)
2424 .icon_position(IconPosition::Start)
2425 .icon_size(IconSize::Small)
2426 .icon_color(Color::Muted)
2427 .full_width()
2428 .key_binding(KeyBinding::for_action_in(
2429 &ToggleContextPicker,
2430 &focus_handle,
2431 window,
2432 cx,
2433 ))
2434 .on_click(|_event, window, cx| {
2435 window.dispatch_action(
2436 ToggleContextPicker.boxed_clone(),
2437 cx,
2438 )
2439 }),
2440 )
2441 .child(
2442 Button::new("mode", "Switch Model")
2443 .label_size(LabelSize::Small)
2444 .icon(IconName::DatabaseZap)
2445 .icon_position(IconPosition::Start)
2446 .icon_size(IconSize::Small)
2447 .icon_color(Color::Muted)
2448 .full_width()
2449 .key_binding(KeyBinding::for_action_in(
2450 &ToggleModelSelector,
2451 &focus_handle,
2452 window,
2453 cx,
2454 ))
2455 .on_click(|_event, window, cx| {
2456 window.dispatch_action(
2457 ToggleModelSelector.boxed_clone(),
2458 cx,
2459 )
2460 }),
2461 )
2462 .child(
2463 Button::new("settings", "View Settings")
2464 .label_size(LabelSize::Small)
2465 .icon(IconName::Settings)
2466 .icon_position(IconPosition::Start)
2467 .icon_size(IconSize::Small)
2468 .icon_color(Color::Muted)
2469 .full_width()
2470 .key_binding(KeyBinding::for_action_in(
2471 &OpenSettings,
2472 &focus_handle,
2473 window,
2474 cx,
2475 ))
2476 .on_click(|_event, window, cx| {
2477 window.dispatch_action(
2478 OpenSettings.boxed_clone(),
2479 cx,
2480 )
2481 }),
2482 ),
2483 )
2484 })
2485 .when_some(configuration_error.as_ref(), |this, err| {
2486 this.child(self.render_configuration_error(
2487 err,
2488 &focus_handle,
2489 window,
2490 cx,
2491 ))
2492 }),
2493 )
2494 })
2495 .when(!recent_history.is_empty(), |parent| {
2496 let focus_handle = focus_handle.clone();
2497 parent
2498 .overflow_hidden()
2499 .p_1p5()
2500 .justify_end()
2501 .gap_1()
2502 .child(
2503 self.render_empty_state_section_header(
2504 "Recent",
2505 Some(
2506 Button::new("view-history", "View All")
2507 .style(ButtonStyle::Subtle)
2508 .label_size(LabelSize::Small)
2509 .key_binding(
2510 KeyBinding::for_action_in(
2511 &OpenHistory,
2512 &self.focus_handle(cx),
2513 window,
2514 cx,
2515 )
2516 .map(|kb| kb.size(rems_from_px(12.))),
2517 )
2518 .on_click(move |_event, window, cx| {
2519 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2520 })
2521 .into_any_element(),
2522 ),
2523 cx,
2524 ),
2525 )
2526 .child(
2527 v_flex()
2528 .gap_1()
2529 .children(recent_history.into_iter().enumerate().map(
2530 |(index, entry)| {
2531 // TODO: Add keyboard navigation.
2532 let is_hovered =
2533 self.hovered_recent_history_item == Some(index);
2534 HistoryEntryElement::new(entry.clone(), cx.entity().downgrade())
2535 .hovered(is_hovered)
2536 .on_hover(cx.listener(
2537 move |this, is_hovered, _window, cx| {
2538 if *is_hovered {
2539 this.hovered_recent_history_item = Some(index);
2540 } else if this.hovered_recent_history_item
2541 == Some(index)
2542 {
2543 this.hovered_recent_history_item = None;
2544 }
2545 cx.notify();
2546 },
2547 ))
2548 .into_any_element()
2549 },
2550 )),
2551 )
2552 .child(self.render_empty_state_section_header("Start", None, cx))
2553 .child(
2554 v_flex()
2555 .p_1()
2556 .gap_2()
2557 .child(
2558 h_flex()
2559 .w_full()
2560 .gap_2()
2561 .child(
2562 NewThreadButton::new(
2563 "new-thread-btn",
2564 "New Thread",
2565 IconName::Thread,
2566 )
2567 .keybinding(KeyBinding::for_action_in(
2568 &NewThread::default(),
2569 &self.focus_handle(cx),
2570 window,
2571 cx,
2572 ))
2573 .on_click(
2574 |window, cx| {
2575 window.dispatch_action(
2576 NewThread::default().boxed_clone(),
2577 cx,
2578 )
2579 },
2580 ),
2581 )
2582 .child(
2583 NewThreadButton::new(
2584 "new-text-thread-btn",
2585 "New Text Thread",
2586 IconName::TextThread,
2587 )
2588 .keybinding(KeyBinding::for_action_in(
2589 &NewTextThread,
2590 &self.focus_handle(cx),
2591 window,
2592 cx,
2593 ))
2594 .on_click(
2595 |window, cx| {
2596 window.dispatch_action(Box::new(NewTextThread), cx)
2597 },
2598 ),
2599 ),
2600 )
2601 .when(cx.has_flag::<feature_flags::AcpFeatureFlag>(), |this| {
2602 this.child(
2603 h_flex()
2604 .w_full()
2605 .gap_2()
2606 .child(
2607 NewThreadButton::new(
2608 "new-gemini-thread-btn",
2609 "New Gemini Thread",
2610 IconName::AiGemini,
2611 )
2612 // .keybinding(KeyBinding::for_action_in(
2613 // &OpenHistory,
2614 // &self.focus_handle(cx),
2615 // window,
2616 // cx,
2617 // ))
2618 .on_click(
2619 |window, cx| {
2620 window.dispatch_action(
2621 Box::new(NewExternalAgentThread {
2622 agent: Some(
2623 crate::ExternalAgent::Gemini,
2624 ),
2625 }),
2626 cx,
2627 )
2628 },
2629 ),
2630 )
2631 .child(
2632 NewThreadButton::new(
2633 "new-claude-thread-btn",
2634 "New Claude Code Thread",
2635 IconName::AiClaude,
2636 )
2637 // .keybinding(KeyBinding::for_action_in(
2638 // &OpenHistory,
2639 // &self.focus_handle(cx),
2640 // window,
2641 // cx,
2642 // ))
2643 .on_click(
2644 |window, cx| {
2645 window.dispatch_action(
2646 Box::new(NewExternalAgentThread {
2647 agent: Some(
2648 crate::ExternalAgent::ClaudeCode,
2649 ),
2650 }),
2651 cx,
2652 )
2653 },
2654 ),
2655 ),
2656 )
2657 }),
2658 )
2659 .when_some(configuration_error.as_ref(), |this, err| {
2660 this.child(self.render_configuration_error(err, &focus_handle, window, cx))
2661 })
2662 })
2663 }
2664
2665 fn render_configuration_error(
2666 &self,
2667 configuration_error: &ConfigurationError,
2668 focus_handle: &FocusHandle,
2669 window: &mut Window,
2670 cx: &mut App,
2671 ) -> impl IntoElement {
2672 match configuration_error {
2673 ConfigurationError::ModelNotFound
2674 | ConfigurationError::ProviderNotAuthenticated(_)
2675 | ConfigurationError::NoProvider => Banner::new()
2676 .severity(ui::Severity::Warning)
2677 .child(Label::new(configuration_error.to_string()))
2678 .action_slot(
2679 Button::new("settings", "Configure Provider")
2680 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2681 .label_size(LabelSize::Small)
2682 .key_binding(
2683 KeyBinding::for_action_in(&OpenSettings, &focus_handle, window, cx)
2684 .map(|kb| kb.size(rems_from_px(12.))),
2685 )
2686 .on_click(|_event, window, cx| {
2687 window.dispatch_action(OpenSettings.boxed_clone(), cx)
2688 }),
2689 ),
2690 ConfigurationError::ProviderPendingTermsAcceptance(provider) => {
2691 Banner::new().severity(ui::Severity::Warning).child(
2692 h_flex().w_full().children(
2693 provider.render_accept_terms(
2694 LanguageModelProviderTosView::ThreadEmptyState,
2695 cx,
2696 ),
2697 ),
2698 )
2699 }
2700 }
2701 }
2702
2703 fn render_tool_use_limit_reached(
2704 &self,
2705 window: &mut Window,
2706 cx: &mut Context<Self>,
2707 ) -> Option<AnyElement> {
2708 let active_thread = match &self.active_view {
2709 ActiveView::Thread { thread, .. } => thread,
2710 ActiveView::ExternalAgentThread { .. } => {
2711 return None;
2712 }
2713 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {
2714 return None;
2715 }
2716 };
2717
2718 let thread = active_thread.read(cx).thread().read(cx);
2719
2720 let tool_use_limit_reached = thread.tool_use_limit_reached();
2721 if !tool_use_limit_reached {
2722 return None;
2723 }
2724
2725 let model = thread.configured_model()?.model;
2726
2727 let focus_handle = self.focus_handle(cx);
2728
2729 let banner = Banner::new()
2730 .severity(ui::Severity::Info)
2731 .child(Label::new("Consecutive tool use limit reached.").size(LabelSize::Small))
2732 .action_slot(
2733 h_flex()
2734 .gap_1()
2735 .child(
2736 Button::new("continue-conversation", "Continue")
2737 .layer(ElevationIndex::ModalSurface)
2738 .label_size(LabelSize::Small)
2739 .key_binding(
2740 KeyBinding::for_action_in(
2741 &ContinueThread,
2742 &focus_handle,
2743 window,
2744 cx,
2745 )
2746 .map(|kb| kb.size(rems_from_px(10.))),
2747 )
2748 .on_click(cx.listener(|this, _, window, cx| {
2749 this.continue_conversation(window, cx);
2750 })),
2751 )
2752 .when(model.supports_burn_mode(), |this| {
2753 this.child(
2754 Button::new("continue-burn-mode", "Continue with Burn Mode")
2755 .style(ButtonStyle::Filled)
2756 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2757 .layer(ElevationIndex::ModalSurface)
2758 .label_size(LabelSize::Small)
2759 .key_binding(
2760 KeyBinding::for_action_in(
2761 &ContinueWithBurnMode,
2762 &focus_handle,
2763 window,
2764 cx,
2765 )
2766 .map(|kb| kb.size(rems_from_px(10.))),
2767 )
2768 .tooltip(Tooltip::text("Enable Burn Mode for unlimited tool use."))
2769 .on_click({
2770 let active_thread = active_thread.clone();
2771 cx.listener(move |this, _, window, cx| {
2772 active_thread.update(cx, |active_thread, cx| {
2773 active_thread.thread().update(cx, |thread, _cx| {
2774 thread.set_completion_mode(CompletionMode::Burn);
2775 });
2776 });
2777 this.continue_conversation(window, cx);
2778 })
2779 }),
2780 )
2781 }),
2782 );
2783
2784 Some(div().px_2().pb_2().child(banner).into_any_element())
2785 }
2786
2787 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
2788 let message = message.into();
2789
2790 IconButton::new("copy", IconName::Copy)
2791 .icon_size(IconSize::Small)
2792 .icon_color(Color::Muted)
2793 .tooltip(Tooltip::text("Copy Error Message"))
2794 .on_click(move |_, _, cx| {
2795 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
2796 })
2797 }
2798
2799 fn dismiss_error_button(
2800 &self,
2801 thread: &Entity<ActiveThread>,
2802 cx: &mut Context<Self>,
2803 ) -> impl IntoElement {
2804 IconButton::new("dismiss", IconName::Close)
2805 .icon_size(IconSize::Small)
2806 .icon_color(Color::Muted)
2807 .tooltip(Tooltip::text("Dismiss Error"))
2808 .on_click(cx.listener({
2809 let thread = thread.clone();
2810 move |_, _, _, cx| {
2811 thread.update(cx, |this, _cx| {
2812 this.clear_last_error();
2813 });
2814
2815 cx.notify();
2816 }
2817 }))
2818 }
2819
2820 fn upgrade_button(
2821 &self,
2822 thread: &Entity<ActiveThread>,
2823 cx: &mut Context<Self>,
2824 ) -> impl IntoElement {
2825 Button::new("upgrade", "Upgrade")
2826 .label_size(LabelSize::Small)
2827 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2828 .on_click(cx.listener({
2829 let thread = thread.clone();
2830 move |_, _, _, cx| {
2831 thread.update(cx, |this, _cx| {
2832 this.clear_last_error();
2833 });
2834
2835 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
2836 cx.notify();
2837 }
2838 }))
2839 }
2840
2841 fn error_callout_bg(&self, cx: &Context<Self>) -> Hsla {
2842 cx.theme().status().error.opacity(0.08)
2843 }
2844
2845 fn render_payment_required_error(
2846 &self,
2847 thread: &Entity<ActiveThread>,
2848 cx: &mut Context<Self>,
2849 ) -> AnyElement {
2850 const ERROR_MESSAGE: &str =
2851 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
2852
2853 let icon = Icon::new(IconName::XCircle)
2854 .size(IconSize::Small)
2855 .color(Color::Error);
2856
2857 div()
2858 .border_t_1()
2859 .border_color(cx.theme().colors().border)
2860 .child(
2861 Callout::new()
2862 .icon(icon)
2863 .title("Free Usage Exceeded")
2864 .description(ERROR_MESSAGE)
2865 .tertiary_action(self.upgrade_button(thread, cx))
2866 .secondary_action(self.create_copy_button(ERROR_MESSAGE))
2867 .primary_action(self.dismiss_error_button(thread, cx))
2868 .bg_color(self.error_callout_bg(cx)),
2869 )
2870 .into_any_element()
2871 }
2872
2873 fn render_model_request_limit_reached_error(
2874 &self,
2875 plan: Plan,
2876 thread: &Entity<ActiveThread>,
2877 cx: &mut Context<Self>,
2878 ) -> AnyElement {
2879 let error_message = match plan {
2880 Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
2881 Plan::ZedProTrial | Plan::ZedFree => "Upgrade to Zed Pro for more prompts.",
2882 };
2883
2884 let icon = Icon::new(IconName::XCircle)
2885 .size(IconSize::Small)
2886 .color(Color::Error);
2887
2888 div()
2889 .border_t_1()
2890 .border_color(cx.theme().colors().border)
2891 .child(
2892 Callout::new()
2893 .icon(icon)
2894 .title("Model Prompt Limit Reached")
2895 .description(error_message)
2896 .tertiary_action(self.upgrade_button(thread, cx))
2897 .secondary_action(self.create_copy_button(error_message))
2898 .primary_action(self.dismiss_error_button(thread, cx))
2899 .bg_color(self.error_callout_bg(cx)),
2900 )
2901 .into_any_element()
2902 }
2903
2904 fn render_error_message(
2905 &self,
2906 header: SharedString,
2907 message: SharedString,
2908 thread: &Entity<ActiveThread>,
2909 cx: &mut Context<Self>,
2910 ) -> AnyElement {
2911 let message_with_header = format!("{}\n{}", header, message);
2912
2913 let icon = Icon::new(IconName::XCircle)
2914 .size(IconSize::Small)
2915 .color(Color::Error);
2916
2917 let retry_button = Button::new("retry", "Retry")
2918 .icon(IconName::RotateCw)
2919 .icon_position(IconPosition::Start)
2920 .icon_size(IconSize::Small)
2921 .label_size(LabelSize::Small)
2922 .on_click({
2923 let thread = thread.clone();
2924 move |_, window, cx| {
2925 thread.update(cx, |thread, cx| {
2926 thread.clear_last_error();
2927 thread.thread().update(cx, |thread, cx| {
2928 thread.retry_last_completion(Some(window.window_handle()), cx);
2929 });
2930 });
2931 }
2932 });
2933
2934 div()
2935 .border_t_1()
2936 .border_color(cx.theme().colors().border)
2937 .child(
2938 Callout::new()
2939 .icon(icon)
2940 .title(header)
2941 .description(message.clone())
2942 .primary_action(retry_button)
2943 .secondary_action(self.dismiss_error_button(thread, cx))
2944 .tertiary_action(self.create_copy_button(message_with_header))
2945 .bg_color(self.error_callout_bg(cx)),
2946 )
2947 .into_any_element()
2948 }
2949
2950 fn render_retryable_error(
2951 &self,
2952 message: SharedString,
2953 can_enable_burn_mode: bool,
2954 thread: &Entity<ActiveThread>,
2955 cx: &mut Context<Self>,
2956 ) -> AnyElement {
2957 let icon = Icon::new(IconName::XCircle)
2958 .size(IconSize::Small)
2959 .color(Color::Error);
2960
2961 let retry_button = Button::new("retry", "Retry")
2962 .icon(IconName::RotateCw)
2963 .icon_position(IconPosition::Start)
2964 .icon_size(IconSize::Small)
2965 .label_size(LabelSize::Small)
2966 .on_click({
2967 let thread = thread.clone();
2968 move |_, window, cx| {
2969 thread.update(cx, |thread, cx| {
2970 thread.clear_last_error();
2971 thread.thread().update(cx, |thread, cx| {
2972 thread.retry_last_completion(Some(window.window_handle()), cx);
2973 });
2974 });
2975 }
2976 });
2977
2978 let mut callout = Callout::new()
2979 .icon(icon)
2980 .title("Error")
2981 .description(message.clone())
2982 .bg_color(self.error_callout_bg(cx))
2983 .primary_action(retry_button);
2984
2985 if can_enable_burn_mode {
2986 let burn_mode_button = Button::new("enable_burn_retry", "Enable Burn Mode and Retry")
2987 .icon(IconName::ZedBurnMode)
2988 .icon_position(IconPosition::Start)
2989 .icon_size(IconSize::Small)
2990 .label_size(LabelSize::Small)
2991 .on_click({
2992 let thread = thread.clone();
2993 move |_, window, cx| {
2994 thread.update(cx, |thread, cx| {
2995 thread.clear_last_error();
2996 thread.thread().update(cx, |thread, cx| {
2997 thread.enable_burn_mode_and_retry(Some(window.window_handle()), cx);
2998 });
2999 });
3000 }
3001 });
3002 callout = callout.secondary_action(burn_mode_button);
3003 }
3004
3005 div()
3006 .border_t_1()
3007 .border_color(cx.theme().colors().border)
3008 .child(callout)
3009 .into_any_element()
3010 }
3011
3012 fn render_prompt_editor(
3013 &self,
3014 context_editor: &Entity<TextThreadEditor>,
3015 buffer_search_bar: &Entity<BufferSearchBar>,
3016 window: &mut Window,
3017 cx: &mut Context<Self>,
3018 ) -> Div {
3019 let mut registrar = buffer_search::DivRegistrar::new(
3020 |this, _, _cx| match &this.active_view {
3021 ActiveView::TextThread {
3022 buffer_search_bar, ..
3023 } => Some(buffer_search_bar.clone()),
3024 _ => None,
3025 },
3026 cx,
3027 );
3028 BufferSearchBar::register(&mut registrar);
3029 registrar
3030 .into_div()
3031 .size_full()
3032 .relative()
3033 .map(|parent| {
3034 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
3035 if buffer_search_bar.is_dismissed() {
3036 return parent;
3037 }
3038 parent.child(
3039 div()
3040 .p(DynamicSpacing::Base08.rems(cx))
3041 .border_b_1()
3042 .border_color(cx.theme().colors().border_variant)
3043 .bg(cx.theme().colors().editor_background)
3044 .child(buffer_search_bar.render(window, cx)),
3045 )
3046 })
3047 })
3048 .child(context_editor.clone())
3049 .child(self.render_drag_target(cx))
3050 }
3051
3052 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
3053 let is_local = self.project.read(cx).is_local();
3054 div()
3055 .invisible()
3056 .absolute()
3057 .top_0()
3058 .right_0()
3059 .bottom_0()
3060 .left_0()
3061 .bg(cx.theme().colors().drop_target_background)
3062 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
3063 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
3064 .when(is_local, |this| {
3065 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
3066 })
3067 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
3068 let item = tab.pane.read(cx).item_for_index(tab.ix);
3069 let project_paths = item
3070 .and_then(|item| item.project_path(cx))
3071 .into_iter()
3072 .collect::<Vec<_>>();
3073 this.handle_drop(project_paths, vec![], window, cx);
3074 }))
3075 .on_drop(
3076 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
3077 let project_paths = selection
3078 .items()
3079 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
3080 .collect::<Vec<_>>();
3081 this.handle_drop(project_paths, vec![], window, cx);
3082 }),
3083 )
3084 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
3085 let tasks = paths
3086 .paths()
3087 .into_iter()
3088 .map(|path| {
3089 Workspace::project_path_for_path(this.project.clone(), &path, false, cx)
3090 })
3091 .collect::<Vec<_>>();
3092 cx.spawn_in(window, async move |this, cx| {
3093 let mut paths = vec![];
3094 let mut added_worktrees = vec![];
3095 let opened_paths = futures::future::join_all(tasks).await;
3096 for entry in opened_paths {
3097 if let Some((worktree, project_path)) = entry.log_err() {
3098 added_worktrees.push(worktree);
3099 paths.push(project_path);
3100 }
3101 }
3102 this.update_in(cx, |this, window, cx| {
3103 this.handle_drop(paths, added_worktrees, window, cx);
3104 })
3105 .ok();
3106 })
3107 .detach();
3108 }))
3109 }
3110
3111 fn handle_drop(
3112 &mut self,
3113 paths: Vec<ProjectPath>,
3114 added_worktrees: Vec<Entity<Worktree>>,
3115 window: &mut Window,
3116 cx: &mut Context<Self>,
3117 ) {
3118 match &self.active_view {
3119 ActiveView::Thread { thread, .. } => {
3120 let context_store = thread.read(cx).context_store().clone();
3121 context_store.update(cx, move |context_store, cx| {
3122 let mut tasks = Vec::new();
3123 for project_path in &paths {
3124 tasks.push(context_store.add_file_from_path(
3125 project_path.clone(),
3126 false,
3127 cx,
3128 ));
3129 }
3130 cx.background_spawn(async move {
3131 futures::future::join_all(tasks).await;
3132 // Need to hold onto the worktrees until they have already been used when
3133 // opening the buffers.
3134 drop(added_worktrees);
3135 })
3136 .detach();
3137 });
3138 }
3139 ActiveView::ExternalAgentThread { .. } => {
3140 unimplemented!()
3141 }
3142 ActiveView::TextThread { context_editor, .. } => {
3143 context_editor.update(cx, |context_editor, cx| {
3144 TextThreadEditor::insert_dragged_files(
3145 context_editor,
3146 paths,
3147 added_worktrees,
3148 window,
3149 cx,
3150 );
3151 });
3152 }
3153 ActiveView::History | ActiveView::Configuration => {}
3154 }
3155 }
3156
3157 fn key_context(&self) -> KeyContext {
3158 let mut key_context = KeyContext::new_with_defaults();
3159 key_context.add("AgentPanel");
3160 match &self.active_view {
3161 ActiveView::ExternalAgentThread { .. } => key_context.add("external_agent_thread"),
3162 ActiveView::TextThread { .. } => key_context.add("prompt_editor"),
3163 ActiveView::Thread { .. } | ActiveView::History | ActiveView::Configuration => {}
3164 }
3165 key_context
3166 }
3167}
3168
3169impl Render for AgentPanel {
3170 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3171 // WARNING: Changes to this element hierarchy can have
3172 // non-obvious implications to the layout of children.
3173 //
3174 // If you need to change it, please confirm:
3175 // - The message editor expands (cmd-option-esc) correctly
3176 // - When expanded, the buttons at the bottom of the panel are displayed correctly
3177 // - Font size works as expected and can be changed with cmd-+/cmd-
3178 // - Scrolling in all views works as expected
3179 // - Files can be dropped into the panel
3180 let content = v_flex()
3181 .key_context(self.key_context())
3182 .justify_between()
3183 .size_full()
3184 .on_action(cx.listener(Self::cancel))
3185 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
3186 this.new_thread(action, window, cx);
3187 }))
3188 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
3189 this.open_history(window, cx);
3190 }))
3191 .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
3192 this.open_configuration(window, cx);
3193 }))
3194 .on_action(cx.listener(Self::open_active_thread_as_markdown))
3195 .on_action(cx.listener(Self::deploy_rules_library))
3196 .on_action(cx.listener(Self::open_agent_diff))
3197 .on_action(cx.listener(Self::go_back))
3198 .on_action(cx.listener(Self::toggle_navigation_menu))
3199 .on_action(cx.listener(Self::toggle_options_menu))
3200 .on_action(cx.listener(Self::increase_font_size))
3201 .on_action(cx.listener(Self::decrease_font_size))
3202 .on_action(cx.listener(Self::reset_font_size))
3203 .on_action(cx.listener(Self::toggle_zoom))
3204 .on_action(cx.listener(|this, _: &ContinueThread, window, cx| {
3205 this.continue_conversation(window, cx);
3206 }))
3207 .on_action(cx.listener(|this, _: &ContinueWithBurnMode, window, cx| {
3208 match &this.active_view {
3209 ActiveView::Thread { thread, .. } => {
3210 thread.update(cx, |active_thread, cx| {
3211 active_thread.thread().update(cx, |thread, _cx| {
3212 thread.set_completion_mode(CompletionMode::Burn);
3213 });
3214 });
3215 this.continue_conversation(window, cx);
3216 }
3217 ActiveView::ExternalAgentThread { .. } => {}
3218 ActiveView::TextThread { .. }
3219 | ActiveView::History
3220 | ActiveView::Configuration => {}
3221 }
3222 }))
3223 .on_action(cx.listener(Self::toggle_burn_mode))
3224 .child(self.render_toolbar(window, cx))
3225 .children(self.render_onboarding(window, cx))
3226 .children(self.render_trial_end_upsell(window, cx))
3227 .map(|parent| match &self.active_view {
3228 ActiveView::Thread {
3229 thread,
3230 message_editor,
3231 ..
3232 } => parent
3233 .relative()
3234 .child(
3235 if thread.read(cx).is_empty() && !self.should_render_onboarding(cx) {
3236 self.render_thread_empty_state(window, cx)
3237 .into_any_element()
3238 } else {
3239 thread.clone().into_any_element()
3240 },
3241 )
3242 .children(self.render_tool_use_limit_reached(window, cx))
3243 .when_some(thread.read(cx).last_error(), |this, last_error| {
3244 this.child(
3245 div()
3246 .child(match last_error {
3247 ThreadError::PaymentRequired => {
3248 self.render_payment_required_error(thread, cx)
3249 }
3250 ThreadError::ModelRequestLimitReached { plan } => self
3251 .render_model_request_limit_reached_error(plan, thread, cx),
3252 ThreadError::Message { header, message } => {
3253 self.render_error_message(header, message, thread, cx)
3254 }
3255 ThreadError::RetryableError {
3256 message,
3257 can_enable_burn_mode,
3258 } => self.render_retryable_error(
3259 message,
3260 can_enable_burn_mode,
3261 thread,
3262 cx,
3263 ),
3264 })
3265 .into_any(),
3266 )
3267 })
3268 .child(h_flex().relative().child(message_editor.clone()).when(
3269 !LanguageModelRegistry::read_global(cx).has_authenticated_provider(cx),
3270 |this| {
3271 this.child(
3272 div()
3273 .size_full()
3274 .absolute()
3275 .inset_0()
3276 .bg(cx.theme().colors().panel_background)
3277 .opacity(0.8)
3278 .block_mouse_except_scroll(),
3279 )
3280 },
3281 ))
3282 .child(self.render_drag_target(cx)),
3283 ActiveView::ExternalAgentThread { thread_view, .. } => parent
3284 .relative()
3285 .child(thread_view.clone())
3286 .child(self.render_drag_target(cx)),
3287 ActiveView::History => parent.child(self.history.clone()),
3288 ActiveView::TextThread {
3289 context_editor,
3290 buffer_search_bar,
3291 ..
3292 } => {
3293 let model_registry = LanguageModelRegistry::read_global(cx);
3294 let configuration_error =
3295 model_registry.configuration_error(model_registry.default_model(), cx);
3296 parent
3297 .map(|this| {
3298 if !self.should_render_onboarding(cx)
3299 && let Some(err) = configuration_error.as_ref()
3300 {
3301 this.child(
3302 div().bg(cx.theme().colors().editor_background).p_2().child(
3303 self.render_configuration_error(
3304 err,
3305 &self.focus_handle(cx),
3306 window,
3307 cx,
3308 ),
3309 ),
3310 )
3311 } else {
3312 this
3313 }
3314 })
3315 .child(self.render_prompt_editor(
3316 context_editor,
3317 buffer_search_bar,
3318 window,
3319 cx,
3320 ))
3321 }
3322 ActiveView::Configuration => parent.children(self.configuration.clone()),
3323 });
3324
3325 match self.active_view.which_font_size_used() {
3326 WhichFontSize::AgentFont => {
3327 WithRemSize::new(ThemeSettings::get_global(cx).agent_font_size(cx))
3328 .size_full()
3329 .child(content)
3330 .into_any()
3331 }
3332 _ => content.into_any(),
3333 }
3334 }
3335}
3336
3337struct PromptLibraryInlineAssist {
3338 workspace: WeakEntity<Workspace>,
3339}
3340
3341impl PromptLibraryInlineAssist {
3342 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
3343 Self { workspace }
3344 }
3345}
3346
3347impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
3348 fn assist(
3349 &self,
3350 prompt_editor: &Entity<Editor>,
3351 initial_prompt: Option<String>,
3352 window: &mut Window,
3353 cx: &mut Context<RulesLibrary>,
3354 ) {
3355 InlineAssistant::update_global(cx, |assistant, cx| {
3356 let Some(project) = self
3357 .workspace
3358 .upgrade()
3359 .map(|workspace| workspace.read(cx).project().downgrade())
3360 else {
3361 return;
3362 };
3363 let prompt_store = None;
3364 let thread_store = None;
3365 let text_thread_store = None;
3366 let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
3367 assistant.assist(
3368 &prompt_editor,
3369 self.workspace.clone(),
3370 context_store,
3371 project,
3372 prompt_store,
3373 thread_store,
3374 text_thread_store,
3375 initial_prompt,
3376 window,
3377 cx,
3378 )
3379 })
3380 }
3381
3382 fn focus_agent_panel(
3383 &self,
3384 workspace: &mut Workspace,
3385 window: &mut Window,
3386 cx: &mut Context<Workspace>,
3387 ) -> bool {
3388 workspace.focus_panel::<AgentPanel>(window, cx).is_some()
3389 }
3390}
3391
3392pub struct ConcreteAssistantPanelDelegate;
3393
3394impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
3395 fn active_context_editor(
3396 &self,
3397 workspace: &mut Workspace,
3398 _window: &mut Window,
3399 cx: &mut Context<Workspace>,
3400 ) -> Option<Entity<TextThreadEditor>> {
3401 let panel = workspace.panel::<AgentPanel>(cx)?;
3402 panel.read(cx).active_context_editor()
3403 }
3404
3405 fn open_saved_context(
3406 &self,
3407 workspace: &mut Workspace,
3408 path: Arc<Path>,
3409 window: &mut Window,
3410 cx: &mut Context<Workspace>,
3411 ) -> Task<Result<()>> {
3412 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3413 return Task::ready(Err(anyhow!("Agent panel not found")));
3414 };
3415
3416 panel.update(cx, |panel, cx| {
3417 panel.open_saved_prompt_editor(path, window, cx)
3418 })
3419 }
3420
3421 fn open_remote_context(
3422 &self,
3423 _workspace: &mut Workspace,
3424 _context_id: assistant_context::ContextId,
3425 _window: &mut Window,
3426 _cx: &mut Context<Workspace>,
3427 ) -> Task<Result<Entity<TextThreadEditor>>> {
3428 Task::ready(Err(anyhow!("opening remote context not implemented")))
3429 }
3430
3431 fn quote_selection(
3432 &self,
3433 workspace: &mut Workspace,
3434 selection_ranges: Vec<Range<Anchor>>,
3435 buffer: Entity<MultiBuffer>,
3436 window: &mut Window,
3437 cx: &mut Context<Workspace>,
3438 ) {
3439 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3440 return;
3441 };
3442
3443 if !panel.focus_handle(cx).contains_focused(window, cx) {
3444 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
3445 }
3446
3447 panel.update(cx, |_, cx| {
3448 // Wait to create a new context until the workspace is no longer
3449 // being updated.
3450 cx.defer_in(window, move |panel, window, cx| {
3451 if let Some(message_editor) = panel.active_message_editor() {
3452 message_editor.update(cx, |message_editor, cx| {
3453 message_editor.context_store().update(cx, |store, cx| {
3454 let buffer = buffer.read(cx);
3455 let selection_ranges = selection_ranges
3456 .into_iter()
3457 .flat_map(|range| {
3458 let (start_buffer, start) =
3459 buffer.text_anchor_for_position(range.start, cx)?;
3460 let (end_buffer, end) =
3461 buffer.text_anchor_for_position(range.end, cx)?;
3462 if start_buffer != end_buffer {
3463 return None;
3464 }
3465 Some((start_buffer, start..end))
3466 })
3467 .collect::<Vec<_>>();
3468
3469 for (buffer, range) in selection_ranges {
3470 store.add_selection(buffer, range, cx);
3471 }
3472 })
3473 })
3474 } else if let Some(context_editor) = panel.active_context_editor() {
3475 let snapshot = buffer.read(cx).snapshot(cx);
3476 let selection_ranges = selection_ranges
3477 .into_iter()
3478 .map(|range| range.to_point(&snapshot))
3479 .collect::<Vec<_>>();
3480
3481 context_editor.update(cx, |context_editor, cx| {
3482 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
3483 });
3484 }
3485 });
3486 });
3487 }
3488}
3489
3490struct OnboardingUpsell;
3491
3492impl Dismissable for OnboardingUpsell {
3493 const KEY: &'static str = "dismissed-trial-upsell";
3494}
3495
3496struct TrialEndUpsell;
3497
3498impl Dismissable for TrialEndUpsell {
3499 const KEY: &'static str = "dismissed-trial-end-upsell";
3500}