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